Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between addition of String Literals and String objects

What is the difference between an addition of String Literal and String Object?

For example

    String s1 ="hello";
    String s2 ="hello1";
    String s3 ="hello" + "hello1";
    String s4 ="hellohello1";
    String s5 = s1 + s2;

    System.out.println(s3 == s4); // returns true
    System.out.println(s3 == s5); // return false
    System.out.println(s4 == s5); // return false

Why do s3/s4 not point to the same location as s5?

like image 529
Kapil Avatar asked Jun 01 '26 22:06

Kapil


1 Answers

Because s1 + s2 is not a constant expression, since s1 and s2 are not final, therefore its result is not interned, i.e. another object is created to represent it, so reference comparison produces false.

JLS 3.10.5 String Literals:

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.

JLS 15.28 Constant Expression:

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • ...
  • Simple names that refer to constant variables (§4.12.4).

JLS 4.12.4 defines final variables.

If you declare s1 and s2 as final, s3 == s5 would be true.

like image 52
axtavt Avatar answered Jun 03 '26 14:06

axtavt



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!