2
String s1 = "Sk";
s1.concat(" Y");
System.out.println("s1 refers to "+s1);

The above code generates the output "Sk" and not "Sk Y". I hope I'm explaining clear enough.Why is this ?

user2864740
  • 60,010
  • 15
  • 145
  • 220
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34

1 Answers1

3

s1.concat(" Y"); doesn't alter s1 (it can't, since Strings are immutable).

It returns a new String :

String s2 = s1.concat(" Y");
System.out.println("s2 refers to "+s2);
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Can You explain immutable in more details or specify a link ? – dumbPotato21 Jun 28 '15 at 09:58
  • @Shashwat There's not much to explain. Immutable object means you can't change its state after you create it. When you write `String s1 = "Sk";`, `s1` refers to an immutable object, so any method you call on `s1` won't change the content of that String. On the other hand, StringBuilder is a mutable object. calling the `append` method of a StringBuilder object changes the content of that object. – Eran Jun 28 '15 at 10:04
  • http://stackoverflow.com/questions/279507/what-is-meant-by-immutable – Stephen C Jun 28 '15 at 11:03