How java handles string literals

in java, I created 2 string literals with the same value

String a = "Hello";
String b = "Hello";

now both of them should have the same link

System.out.println(a==n); // returns true

but when i do

b+=" World";
System.out.println(a==b); // returns false

Now I have 2 questions

1. Why a and b do not refer to the same object after the operation "b + ="? 2. How can I change line b without error? (Because I read the String class unchanged)

+1
source share
3 answers

The reason you can change bis because you technically create a new String object and assign it to an existing link.

b += " World"

coincides with

b = b + " World";

b String. , , a b , b , , a "Hello World", a==b .

String StringBuffer StringBuilder. .append() .

+4
  • b+=" World", , , .

  • , b. final, .

+2
  • a b String. b , .

  • , "" , . .

0

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


All Articles