File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Immutable Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Immutable Strings" Watch "Immutable Strings" New topic

Immutable Strings

Rahul Bajaj
Ranch Hand

Joined: Sep 21, 2004
Posts: 45
As everyone must be knowing Strings are immutable but I have little confusion here.Look at the code:

String s1 = "Hello";
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

Joined: Sep 28, 2004
Posts: 1228
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.


Thanks & regards, Srini
MCP, SCJP-1.4, NCFM (Financial Markets), Oracle 9i - SQL ( 1Z0-007 ), ITIL Certified
Arnaud Burlet
Ranch Hand

Joined: Oct 08, 2004
Posts: 31

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

got it ?

John Dell'Oso
Ranch Hand

Joined: Apr 08, 2004
Posts: 130

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.

Rahul Bajaj
Ranch Hand

Joined: Sep 21, 2004
Posts: 45
Thanks everyone for helping out.I got the idea.
I agree. Here's the link:
subject: Immutable Strings
jQuery in Action, 3rd edition