Java string internship, what is the guarantee?

The problem boils down to the following code:

// setup
String str1 = "some string";
String str2 = new String(str1);
assert str1.equals(str2);
assert str1 != str2;
String str3 = str2.intern();

// question cases
boolean case1 = str1 == "some string";
boolean case2 = str1 == str3;

Does the Java standard provide any guarantee for the values of case1 and case2? Of course, it would be nice to link to the relevant parts of the Java specification

Yes, I read all so similar questions and found no repetition, because I didn't find an answer to this question No, this is not about the wrong idea of "optimizing" string comparisons by replacing equals with = =

Solution

Here is your JLS quotation, section 3.10 5:

package testPackage;
class Test {
        public static void main(String[] args) {
                String hello = "Hello",lo = "lo";
                System.out.print((hello == "Hello") + " ");
                System.out.print((Other.hello == hello) + " ");
                System.out.print((other.Other.hello == hello) + " ");
                System.out.print((hello == ("Hel"+"lo")) + " ");
                System.out.print((hello == ("Hel"+lo)) + " ");
                System.out.println(hello == ("Hel"+lo).intern());
        }
}

class Other { static String hello = "Hello"; }
package other;

public class Other { static String hello = "Hello"; }

Combined with Javadoc interns, you have enough information to infer that both of your cases will return to reality

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>