根据字符串#intern(),如果在String Pool中找到字符串,则intern
方法应该返回String Pool中的字符串,否则将在String池中添加新的String对象,并返回该字符串的引用。
所以我试着这样做:
String s1 = "Rakesh";
String s2 = "Rakesh";
String s3 = "Rakesh".intern();
if ( s1 == s2 ){
System.out.println("s1 and s2 are same"); // 1.
}
if ( s1 == s3 ){
System.out.println("s1 and s3 are same" ); // 2.
}
我预计s1 and s3 are same
将在S3中断时打印,而s1 and s2 are same
将不会打印。但结果是:两行都打印出来了。因此,这意味着,默认情况下,字符串常量是INTERN.但如果是这样的话,为什么我们需要intern
方法呢?换句话说,我们应该在什么时候使用这种方法?