Java string concatenation and interning

Question 1

String a1 = "I Love" + " Java";
String a2 = "I Love " + "Java";
System.out.println( a1 == a2 ); // true

String b1 = "I Love";
b1 += " Java";
String b2 = "I Love ";
b2 += "Java";
System.out.println( b1 == b2 ); // false

In the first case, I understand that this is a concatenation of two string literals, so the result of "I Love Java" will be interned, giving the result true. However, I am not sure about the second case.

Question 2

String a1 = "I Love" + " Java"; // line 1
String a2 = "I Love " + "Java"; // line 2

String b1 = "I Love";
b1 += " Java";
String b2 = "I Love ";
b2 += "Java";
String b3 = b1.intern();
System.out.println( b1 == b3 ); // false

The above returns false, but if I comment on lines 1 and 2, it returns true. Why is this?

+4
source share
3 answers

The first part of your question is simple: the Java compiler considers the concatenation of several string literals as a single-line literal, i.e.

"I Love" + " Java"

and

"I Love Java"

are two identical string literals that are properly interned.

+= , b1 b2 .

. , b1.intern() b1 - String, . a1 a2, a1 b1.intern(). a1 a2, , , b1.intern() b1.

+4

intern() docs

. 3.10.5 Java ™.

JLS 3.10.5

  • , (§15.28), , , .
    • , , .

b1 . .

+1

1:

==. == (int, long, float, double boolean) . , varibales (a1, a2, b1, b2) ( , ), ( ==).

b1.equals(b2), , .

Java , , ( ), , . , a1 a2 (==).

( ). , . , , , == false. .

2: @dasblinkenlight .

0
source

Source: https://habr.com/ru/post/1681692/


All Articles