String s1 = new String("hello");
String s2 = "hello";
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
String s3 = String.valueOf("hello");
System.out.println(s3);
System.out.println(s3==s2);//true
System.out.println(s3==s1);//false
String s1 = new String("hello");
不管方法區常量池是否有"hello"存在,都會在堆內存new()一個新的String對象,如果常量池中存在該字符串,則該對象指向常量池中的字符串,否則在常量池中創建新的常量,然後該對象的地址值賦給s1變量。
String s2 = "hello";
String s3 = String.valueOf("hello")
從測試結果來看,都是現在常量池尋找,所以s2 == s3爲true
其他練習:
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
String s3 = new String("hello");
String s4 = "hello";
System.out.println(s3 == s4);// false
System.out.println(s3.equals(s4));// true
String s5 = "hello";
String s6 = "hello";
System.out.println(s5 == s6);// true
System.out.println(s5.equals(s6));// true
練習2:
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1 + s2);// false
System.out.println(s3.equals((s1 + s2)));// true
System.out.println(s3 == "hello" + "world");// false 這個我們錯了,應該是true
System.out.println(s3.equals("hello" + "world"));// true
解析:s1 + s2 在編譯的時候是先在堆內存創建一個新的String對象,再把s1和s2拼接的結果賦給新對象,所以雖然s3和s1+s2的字符串內容一樣,但是s3==s1+s2爲false