Immutable Strings Object

How String object is immutable and why?

Questions by vyasbsraju

Showing Answers 1 - 3 of 3 Answers

ramnath_19

  • Jan 3rd, 2008
 

Ur question can be answered with an example  : 

String s = "here it goes";
s.toUppercase();
This does not modify the variable s at all. Instead, a new String object is created with all the characters of s changed to upper case. Since the new object is not assigned to anything, it is simply loses all references (as the toUpperCase method has completed) and is eventually garbage collected.

 On the other hand, you could write it like this:
String s = "here it goes";
s = s.toUppercase();
In this example, s is now in all upper case letters, but it is not the same object as the one that was instantiated in the first line. The new String object that is returned from toUpperCase becomes assigned to s, and the original object loses its last reference and gets garbage collected.


Hope this will make things clear.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions