Thursday 12 June 2014

Strings Immutability

Strings are immutable in Java, i.e. once a string object created, its value can't be changed. Lets see it by detailed example.

class StringImmutable{
 public static void main(String args[]){
  String s1 = "Hello";
  String s2 = s1;
  
  System.out.println("s1 = " + s1);
  System.out.println("s2 = " + s2);
  
  s1 = "How Are You";
  
  System.out.println("s1 = " + s1);
  System.out.println("s2 = " + s2);
 }
}

Output
s1 = Hello
s2 = Hello
s1 = How Are You
s2 = Hello

Observe the below lines
   String s1 = "Hello";
   String s2 = s1;

Here s1 and s2 are two reference variables that points to the object with content “Hello”.

s1 = "How Are You";

No s1 points to the object with content "How Are You". But it won't replace the contents of the string object “Hello”.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment