prometheuspk
prometheuspk

Reputation: 3815

Java references. Does Java make 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 true if the references are same. What I want to know is, Does Java check the content of string literals before creating their objects?

Upvotes: 3

Views: 142

Answers (2)

Matt Ball
Matt Ball

Reputation: 359966

You're seeing one of the side effects of Java string interning. From the JLS §3.10.5:

...A string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Lots more reading on SO, especially:

Upvotes: 4

Martijn Courteaux
Martijn Courteaux

Reputation: 68887

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:

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

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

Strings, build at runtime are not interned automatically.

Upvotes: 3

Related Questions