Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java references. Does Java make a special check with string literals?

Tags:

java

reference

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?

like image 210
prometheuspk Avatar asked Sep 01 '26 21:09

prometheuspk


2 Answers

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:

  • If == compares references in Java, why does it evaluate to true with these Strings?
  • Java string intern and literal
  • When is it beneficial to flyweight Strings in Java?
  • How do I compare strings in Java?
like image 117
Matt Ball Avatar answered Sep 03 '26 11:09

Matt Ball


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.

like image 22
Martijn Courteaux Avatar answered Sep 03 '26 13:09

Martijn Courteaux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!