Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does string literal concatenation work in Java?

Tags:

java

string

If we are concatenating two string literals in Java, then how and where does the new String get created?

class StringClass {
    public static void main(String[] args) {

        String a = "java";
        String b = "ja";
        String c = "va";
        String d = b + c;

        System.out.println(a == d);
    }

}

If both a and d are part of the string pool, then why a == d return false?

Is d not a part of the string pool?

like image 551
Aniket_Mishra Avatar asked Jun 24 '26 21:06

Aniket_Mishra


1 Answers

Since b + c is not a constant expression it is evaluated at runtime. A string pool entry is not created there.

"Is d not a part of string pool?"

CORRECT. The value of d has not been added to the string pool. Only strings resulting from a constant expression are added to the string pool automatically.

A constant expression is defined in JLS 15.29. I will not reproduce it here in its entirety, but I encourage you to take the time to read it. Intuitively, a constant expression is one that can be evaluated at compile time, but it is a bit more complicated than that.

The reason that b + c is NOT a constant expression (here) is that b and c were not declared as final.


Having said all of the above, there is really no need to understand the details of the string pool and when something will be added to it. All you really need to do is follow this "rule":

Do not use == to test if String values are equal. Use the String.equals(Object) method. Always.

Also, do not use String.intern() directly. In recent versions of Java, GC's are able to automatically de-dup any long-lived String objects*. If you are using intern() so that you can use ==,

  1. it is a micro-optimization that could well not be worth it (since interning and the string pool itself incur runtime overheads), and

  2. it is risky ... since you have to be sure that you intern all of the String objects you are going to test ... to avoid incorrect results, and

  3. it makes your code more complicated and harder to reason about.


* Actually, the GC only dedups the strings' respective internal backing arrays. The affected strings are still distinct, so == still doesn't work. The deduping (currently) just saves space ... modulo some 2nd order performance issues.

like image 178
Stephen C Avatar answered Jun 26 '26 10:06

Stephen C



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!