1

in java, i have created 2 string literals having same value

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

now both of them should have same reference

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 here
1. why a and b are not referencing to same object after 'b+=' operation? 2. how come i'm able to change string b without any error?(because i have read String class is immutable)

Shashi
  • 746
  • 10
  • 39
  • 5
    This question has been asked and answered hundreds of times on SO. Please search first. – Rohit Jain Aug 06 '13 at 15:51
  • 1
    [How can a string be initialized using “ ”?](http://stackoverflow.com/questions/17489250/how-can-a-string-be-initialized-using/17489410#17489410) – Suresh Atta Aug 06 '13 at 15:52
  • possible duplicate of [Java String Pool](http://stackoverflow.com/questions/2486191/java-string-pool) or really [How do I compare Strings in Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) among *numerous* others. – Brian Roach Aug 06 '13 at 15:54
  • may be i was not looking hard enough but i did searched SO for this .. and quite frankly i didn't found anywhere else that += will create a new instance. i was curious so i had to post a new question and i got my answer.:) – Shashi Aug 06 '13 at 16:26
  • Yes, I think the reason that this is the most-asked question is that it is difficult to think of a phrase to search for. It is just where text-oriented search fails. – Marko Topolnik Aug 06 '13 at 16:38

3 Answers3

4

The reason you can change b is because you're technically making a new String object and assigning it to the existing reference.

b += " World"

is the same as

b = b + " World";

b is technically pointing to a new String object. So to start out, a and b are pointing to the same object, but when b is modified it is now a different object, so a will not equal "Hello World" and a==b will now be false.

For examples of mutable String classes, try StringBuffer or StringBuilder. You can use their .append() method to add to the string, along with other methods to modify it.

framauro13
  • 797
  • 2
  • 8
  • 18
2
  1. When you do b+=" World" you are creating a new string instance, of course this does not point to the same old string anymore.

  2. You are not changing the old string, instead you are creating a new string and assigning it to the variable b. Use the final modifier if you want to always refer to the same object with that variable.

Zavior
  • 6,412
  • 2
  • 29
  • 38
0
  1. a and b are pointing to a String object. Modifying b, means you are now pointing to a new object.

  2. Because Strings are immutable, when you "modify" a string, a new object is created. That's why the second is no longer the same.

Samir Seetal
  • 392
  • 6
  • 8