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 true if the references are same. What I want to know is, Does Java check the content of string literals before creating their objects?
It is the compiler that does the string interning. So at compile time identical strings are optimised. So I think the answer you want is “no”. The Virtual Machine doesn’t do it, it is the compiler. You can call
String.intern()to acquire the shared string object in the string pool:Strings, build at runtime are not interned automatically.