All for Joomla All for Webmasters

Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

Once string object is created its data or state can’t be changed but a new string object is created.

Let’s try to understand the immutability concept by the example given below:

  1. class Testimmutablestring{
  2.  public static void main(String args[]){
  3.    String s=“Sachin”;
  4.    s.concat(” Tendulkar”);//concat() method appends the string at the end
  5.    System.out.println(s);//will print Sachin because strings are immutable objects
  6.  }
  7. }
Output:Sachin

But if we explicitely assign it to the reference variable, it will refer to “Sachin Tendulkar” object.For example:

  1. class Testimmutablestring1{
  2.  public static void main(String args[]){
  3.    String s=“Sachin”;
  4.    s=s.concat(” Tendulkar”);
  5.    System.out.println(s);
  6.  }
  7. }
Output:Sachin Tendulkar

n such case, s points to the “Sachin Tendulkar”. Please notice that still sachin object is not modified.


Why string objects are immutable in java?

Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object “sachin”.If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
PinIt
submit to reddit

Leave a Reply

Top