Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between mutable and immutable String in java

As per my knowledge,

a mutable string can be changed, and an immutable string cannot be changed.

Here I want to change the value of String like this,

String str="Good"; str=str+" Morning"; 

and other way is,

StringBuffer str= new StringBuffer("Good"); str.append(" Morning"); 

In both the cases I am trying to alter the value of str. Can anyone tell me, what is difference in both case and give me clear picture of mutable and immutable objects.

like image 337
Raghu Avatar asked Aug 05 '14 12:08

Raghu


Video Answer


2 Answers

Case 1:

String str = "Good"; str = str + " Morning"; 

In the above code you create 3 String Objects.

  1. "Good" it goes into the String Pool.
  2. " Morning" it goes into the String Pool as well.
  3. "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap.

Note: Strings are always immutable. There is no, such thing as a mutable String. str is just a reference which eventually points to "Good Morning". You are actually, not working on 1 object. you have 3 distinct String Objects.


Case 2:

StringBuffer str = new StringBuffer("Good");  str.append(" Morning"); 

StringBuffer contains an array of characters. It is not same as a String. The above code adds characters to the existing array. Effectively, StringBuffer is mutable, its String representation isn't.

like image 59
TheLostMind Avatar answered Oct 04 '22 04:10

TheLostMind


What is difference between mutable and immutable String in java

immutable exist, mutable don't.

like image 36
Philipp Sander Avatar answered Oct 04 '22 04:10

Philipp Sander