Search code examples
javastringpool

why these strings are not pointing to the same object in java?


I know that if I have 2 string variables with the same value, they point to the same string object because of the java string pool.

Here is an example:

String test = "1234";
String test2 = "1234";
    
System.out.println(test == test2);
System.out.println("1234" == test2);

the output is the following:

true
true

But if I have the following code, it prints that they aren't the same object

String test = "1234";
int i = 1234;
String s = "" + i;
    
System.out.println(test == s);
System.out.println("1234" == s);

Output:

false
false

Anyone would explain to me the reason for that behavior, please?


Solution

  • "" + i; is not a constant expression, so it is not interned. If i were final or it was directly written as "" + 1234, then the value would be interned.

    §3.10.5. String Literals:

    Moreover, 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.

    §15.28. Constant Expressions:

    A 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:
    • Literals of primitive type and literals of type String (§3.10.1, §3.10.2, §3.10.3, §3.10.4, §3.10.5)
    • Casts to primitive types and casts to type String (§15.16)
    • The unary operators +, -, ~, and ! (but not ++ or --) (§15.15.3, §15.15.4, §15.15.5, §15.15.6)
    • The multiplicative operators *, /, and % (§15.17)
    • The additive operators + and - (§15.18)
    • The shift operators >, and >>> (§15.19)
    • The relational operators , and >= (but not instanceof) (§15.20)
    • The equality operators == and != (§15.21)
    • The bitwise and logical operators &, ^, and | (§15.22)
    • The conditional-and operator && and the conditional-or operator || (§15.23, §15.24)
    • The ternary conditional operator ? : (§15.25)
    • Parenthesized expressions (§15.8.5) whose contained expression is a constant expression.
    • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
    • Qualified names (§6.5.6.2) of the form TypeName . Identifier that refer to constant variables (§4.12.4).