// 初始化String s1 = "Hello World";System.out.println("s1 is \"" + s1 + "\"");String s2 = s1;System.out.println("s2 是对 s1 的另一个引用.");String s3 = new String(s1);System.out.println("s3 是 s1 的副本.");// 等号比较 '==' 比较这两个对象是否是同一个对象。System.out.println("Compared by '==':");// true since string is immutable and s1 is binded to "Hello World"// true 因为字符串是不可变的并且 s1 绑定到“Hello World”System.out.println("s1 and \"Hello World\": " + (s1 == "Hello World")); // true// true since s1 and s2 is the reference of the same object// true 因为 s1 和 s2 是同一个对象的引用System.out.println("s1 and s2: " + (s1 == s2)); // true// false since s3 is refered to another new object// false 因为 s3 引用了另一个新对象System.out.println("s1 and s3: " + (s1 == s3)); // false// compare using 'equals' 比较字符串中所包含的内容是否相同System.out.println("Compared by 'equals':");System.out.println("s1 and \"Hello World\": " + s1.equals("Hello World"));System.out.println("s1 and s2: " + s1.equals(s2)); // trueSystem.out.println("s1 and s3: " + s1.equals(s3)); // true// compare using 'compareTo' // 字符串与字符对象比较System.out.println("Compared by 'compareTo':");System.out.println("s1 and \"Hello World\": " + (s1.compareTo("Hello World") == 0)); // trueSystem.out.println("s1 and s2: " + (s1.compareTo(s2) == 0)); // trueSystem.out.println("s1 and s3: " + (s1.compareTo(s3) == 0)); // trueSystem.err.println("===============");/** * 字符串不可变 *//* String str1 = "Hello World";str1[5] = ',';System.out.println(str1);*//** * 针对 Java 中出现的此问题,提供了以下解决方案: * * 如果你确实希望你的字符串是可变的,则可以使用 toCharArray 将其转换为字符数组。 * 如果你经常必须连接字符串,最好使用一些其他的数据结构,如 StringBuilder 。 */String s = "";int n = 10000; for (int i = 0; i < n; i++) { s += "hello"; }}