String、StringBuffer、StringBuilder的区别

114 阅读1分钟

String

java 8 内部是使用char数组来储存数据

public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ private final char value[]; }

Java 9之后改用byte数组存储字符串,同时使用 coder 来标识使用了哪种编码。

public final class String implements java.io.Serializable, Comparable<String>, CharSequence { 
private final byte[] value; 
private final byte coder; 
}

String是不可变的,字符串为什么会发生改变?

String a = “hello”;
String b = “world”;
a = a + b; /// a = “helloworld”/

原因是:String 在用+号拼接的时候,jvm默认是使用StringBuilder来拼接, StringBuilder 是可变的字符串类型。 toString()方法会生成一个新对象。

String +int 拼接的时候会转为String

int a =12;
String str =“hello”+a;

空字符串和null拼接,结果是null

String str = null;
str = str + “”;
System.out.println(str);

检测字符串是否相等

  • 对于基本数据类型来说, == 比较的是值是否相同;
  • 对于引用数据类型来说, == 比较的是内存地址是否相同。
String str1 = *new* String(“hello”); 
String str2 = *new* String(“hello”);
System.out.println(str1 == str2); /// false/

StringBuffer、StringBuilder

String s = “Hello”;
s += “World”;

这段代码会产生3个字符串,分别为Hello、World、Hello World、+号在使用的时候会new 一个对象来接收Hello World。

StringBuffer线程安全,内部使用synchronize 修饰方法。

StringBuilder单线程模式,拼接字符串效率更高。