根据String #intern(),intern如果在String池中找到String,则该方法应该从String池返回String,否则将在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.
}
Run Code Online (Sandbox Code Playgroud)
我期待s1 and s3 are same将被打印为s3被实习,并且s1 and s2 are same不会被打印.但结果是:两行都打印出来.这意味着,默认情况下,字符串常量被实现.但如果是这样,那么为什么我们需要这种intern方法呢?换句话说,我们什么时候应该使用这种方法?