String s1 = "Hello World";
System.out.println("s1 is \"" + s1 + "\"");
String s2 = s1;
System.out.println("s2 is another reference to s1.");
String s3 = new String(s1);
System.out.println("s3 is a copy of s1.");
// compare using '=='
System.out.println("Compared by '==':");
// true since string is immutable and s1 is binded to "Hello World"
System.out.println("s1 and \"Hello World\": " + (s1 == "Hello World"));
// true since s1 and s2 is the reference of the same object
System.out.println("s1 and s2: " + (s1 == s2));
// false since s3 is refered to another new object
System.out.println("s1 and s3: " + (s1 == s3));
这里s1直接赋值
s2是s1的另一个引用
s3是s1的复制
如果使用==进行检查
s1=="Hello World"
s1==s2
s1!=s3
字符串连接
在java中,字符串长度不可变;在连接时首先为新字符串分配足够的空间,复制旧字符串中的内容并附加到新字符串。
public static void main(String[] args) {
String s = "";
int n = 10000;
for (int i = 0; i < n; i++) {
s += "hello";
}
System.out.println(s);
}
StringBuilder的效率比StringBuffer要高一些,但是StringBuilder线程不安全,StringBuffer是线程安全的。