比较程序下面的两个程序:
eg1:
public class NewClass {
    public static void main(String[] args) {
        String str1 = new String("abc");
        str1 = str1.intern();
        String str2 = "abc";
        
        if (str1 == (str2)) {
            System.out.println("true");
        } else {
            System.out.println("false");
        }
    }
}
/**  输出结果为:true
/eg2:
public class NewClass {
    public static void main(String[] args) {
        String str1 = new String("abc");
        // 区别在此
        str1.intern();
        String str2 = "abc";        
        if (str1 == (str2)) {
            System.out.println("true");
        } else {
            System.out.println("false");
        }
    }
}
/**  输出结果为:false
/为什么“str1 = str1.intern();”可以将字符写入字符池;“str1.intern();”无法将字符写入字符池。

解决方案 »

  1.   

    调用String对象的intern方法的说明解释如下:
    当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(用 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并返回此 String 对象的引用。 你第二个程序中执行“str1.intern();”后,实际上已经把字符串写入到字符池了,但是你没有返回此 String 对象的引用啊,str的依然是“String str1 = new String("abc");”执行后的引用啊!