为什么==操作在字符串java中使用“”+失败

时间:2018-01-17 06:35:11

标签: java string

String s1 = "java";

String s2 = "java";

System.out.println(s1==s2);  //true
System.out.println(""+s1==s2); //false

输出为何如此?

在第二种情况下只添加了“”引号。

1 个答案:

答案 0 :(得分:3)

  • ==比较两个字符串对象的引用,对于上述两种情况,它们会有所不同。
  • .equals()比较2个字符串对象的值
  • 对于String对象,String pool将通过将具有相同值的不同String对象重新组合到内存中的相同位置来节省一些内存。

请查看以下代码以了解其工作原理:

String s1 = "java";//first string
String s2 = "java";//thanks to string pool the s2 is actually using the same memory location as s1 (saving space for same value string objects)

System.out.println(s1==s2);  //true ref comparison equals thanks to string pool intervention
System.out.println(""+s1==s2); //false (the resulting string of ""+s1 is stored in a different place in memory than s4
System.out.println(""+(s1==s2));//true due to string pool
System.out.println(s1.equals(s2));  //true -> value comparison
System.out.println(s2.equals(""+s1)); //true -> value comparison


String s3 = new String("java");//this construction does not let the string pool intervene
String s4 = new String("java");//2 different memory locations for those 2 objects

System.out.println(s3==s4);  //false no string pool intervention -> 2 different memory locations
System.out.println(""+s3==s4); //false false (the resulting string of ""+s3 is stored in a different place in memory than s4
System.out.println(""+(s3==s4));//false no string pool intervention -> 2 different memory locations
System.out.println(s3.equals(s4));  //true -> value comparison
System.out.println(s4.equals(""+s3)); //true -> value comparison