Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Immutable Strings

 
Rahul Bajaj
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
As everyone must be knowing Strings are immutable but I have little confusion here.Look at the code:

String s1 = "Hello";
s1.concat("World");
System.out.println(s1); //Output will be Hello
//but if I say
System.out.println (s1.concat("World"); //Output is HelloWorld

so its confusing???can someone explain me why is it so? it works with all methods of String class like touppercase() ,tosubsstring();...
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Miki,

String is immutable right ..
But when ever you do any string operation like concatenation or any other String updations a new string object will be created for each operation.
and the value is stored.

So when you are dealing with more string operations.. It's better to use StringBuffer class which 'll increase the performance.

Srini
 
Arnaud Burlet
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

like you said, Strings are immutable. All the operation on a String don't affect your String, they return a new one !


got it ?

Arnaud
 
John Dell'Oso
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Miki,

As the other guys have mentioned, when invoking methods such as concat on String objects a new string is returned. Consider this code for example:



If you run this code, you will see "HelloWorld" as the last line of output.
HTH

Cheers,
 
Rahul Bajaj
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone for helping out.I got the idea.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic