方式一:直接复制 String s = "hsp";
方式二:调用构造器 String s2 = new String("hsp");
String a = "abc"; String b = "abc"; System.out.println(a.equals(b)); // true System.out.println(a == b); // true
String a = "hsp"; // a指向常量池 String b = new String("hsp"); // b指向堆中的对象 System.out.println(a.equals(b)); // true System.out.println(a == b); // false // 当调用intern方法时,如果池已经包含与equals(Object)方法确定的相当于此String对象的字符串,则返回来自池的字符串。 否则,此String对象将添加到池中,并返回对此String对象的引用。 b.intern()方法最终返回的是常量池的地址 System.out.println(a == b.intern()); // true System.out.println(b == b.intern()); // false
String s1 = "hspedu"; // String s2 = "java"; // String s4 = "java"; // String s3 = new String("java"); // System.out.println(s2 == s3);//false System.out.println(s2 == s4);//true System.out.println(s2.equals(s3)); // true System.out.println(s1 == s2); // false
Person p1 = new Person(); p1.name = "hspedu"; Person p2 = new Person(); p2.name = "hspedu"; System.out.println(p1.name.equals(p2.name)); // true System.out.println(p1.name == p2.name);//true System.out.println(p1.name == "hspedu");//true String s1 = new String("bcde"); String s2 = new String("bcde"); System.out.println(s1 == s2); // false
// 1. 以下语句创建了几个对象 2个常量池中字符串常量对象 String s1 = "hello"; s1 = "haha";
// 创建了几个对象 1个 编译器会优化 ==>等价于 String a = "helloabc"; String a = "hello" + "abc";
String a = "hello"; String b = "abc"; String c = a+b; String d = "helloabc"; String e = "hello" + "abc"; System.out.println(c == d);// false System.out.println(d == e);// true // 创建了几个对象 3个对象 分析String c = a + b;怎么执行的 //1. 创建一个StringBuilder //2. 执行sb.append("hello"); //3. 执行sb.append("abc"); //4. 调用sb.toString(); //5. 最后其实c指向堆中的对象(String) value[] -> 池中 "helloabc"
String s1 = "hspedu"; String s2 = "java"; String s5 = "hspedujava"; Strring s6 = (s1 + s2).intern(); System.out.println(s5 == s6); // true System.out.println(s5.equals(s6)); // true
public class Test1 { String str = new String("hsp"); final char[] ch = {'j', 'a', 'v', 'a'}; public void change(String str, char[] ch) { str = "java"; ch[0] = 'h'; } public static void main(String[] args) { Test1 ex = new Test1(); ex.change(ex.str, ex.ch); System.out.print(ex.str + "and"); System.out.println(ex.ch); // ex.change中理解方法栈中指向的线断了,不影响main栈 // hsp and hava } }
// String -> StringBuffer String s = "hello"; StringBuffer b1 = new StringBuffer(s);// 返回的才是StringBuffer对象对String本身没有影响 StringBuffer b2 = new StringBuffer(); b2.append(s); // StringBuffer -> String String s2 = b1.toString(); String s3 = new String(b1);
String str = null; // ok StringBuffer sb = new StringBuffer(); // ok sb.append(str); // 调用父类的appendNull 将null转为"null"字符串 System.out.println(sb.length()); // 4 System.out.println(sb); // null StringBuffer sb1 = new StringBuffer(str); // super(str.length() + 16) 空指针异常 System.out.println(sb1);