String的那点小事儿

1、== 比较的是什么?

 1 package xupengwei.string;
 2 /** 
 3  * @describe:
 4  * @author chenmo-xpw
 5  * @version 2014年5月22日 下午1:00:42
 6  */
 7 public class StringDemo {
 8     public static void main(String[] args) {
 9         String s1 = "hello chenmo";
10         String s2 = "hello chenmo";
11         
12         System.out.println(s1 == s2);
13         
14         String s3 = new String("hello chenmo");
15         String s4 = new String("hello chenmo");
16         
17         System.out.println(s3 == s4);
18     }
19 }

结果

true
false

2、其实,这些不难,只是细节问题。

对于(字符串) s1、 s2,当且仅当, s1  和 s2 的内容相同,且 s1 和 s2 的地址相同时, s1 == s2。

可能,你有些疑问了,为什么在下面的代码,s1 和 s2 是同一个对象

String s1 = "hello chenmo";

String s2 = "hello chenmo";

这涉及到 JVM 对字符串的处理方式了,对于字符直接量(如上的“hello chenmo”),JVM 会使用一个字符串池来缓存它们,当第一次使用该字符直接量时,
JVM会将它放入字符串池。当我们再次使用该字符串时,无须重新创建一个新的字符串,而是直接让引用指向字符串池中已有的字符串。所以,上面的s1 、 s2
都是指向同一个对象,既然是同一个对象,地址就相同了。所以s1 == s2 。那 s3 != s4,这又是为什么么?很简单,s3、s4 都是 通过new来创建新对象,
很自然,s3、 s4指向的对象是不同的!
原文地址:https://www.cnblogs.com/chenmo-xpw/p/3745456.html