Links to Java. Is Java a special check with string literals?

public class Test {
    int multiple;
    public static void main(String[] args){

        String string1 = "string";
        String string2 = "string";
        String string4 = "Changed";

        String string3 = new String("string");

        System.out.println("string1 == string2: " + (string1 == string2));\\true
        System.out.println("string1 == string4: " + (string1 == string4));\\false
        System.out.println("string1 == string3: " + (string1 == string3));\\false

    }


}

I understand that the operator ==will return trueif the links match. I want to know if Java checks the contents of string literals before creating their objects?

+3
source share
2 answers

This is a compiler that does string interning. Therefore, during compilation, identical lines are optimized. Therefore, I think the answer you want is no. The virtual machine does not do this, it is a compiler. You can call String.intern()to get a common string object in the string pool:

String str1 = "string";
String str2 = new String("string");
String str3 = str2.intern();

str1 == str2 // false
str2 == str3 // false
str1 == str3 // true

Lines created at runtime are not executed automatically.

+3
source
+4

All Articles