• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is string immutable?

 
Venkat Ramsimha
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider the following code:

class StringDemonstration1
{
String i = "ramu";//line1
String j = "somu";//line2
public void add()
{
String firstname = "venkat";
String lastname = "ramsimha";
String name = firstname + lastname;
System.out.println("" +name);
}


}

class StringDemonstration2 extends StringDemonstration1
{
public static void main(String args[])
{
StringDemonstration2 sd = new StringDemonstration2();
sd.i = "vijay";//line3
System.out.println("" +sd.i);
sd.j = "pal";//line4
System.out.println("" +sd.j);
sd.add();
}



}

we know that strings are objects in javacode which are "immutable" that is there value once assigned cannot be changed.so if that is the case in the above program for line1 and line2 the values shouild not be changed but strangely when i compile the program iam getting the output as "vijaypal"

anybody helpout me...
tx
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String objects are truly immutable but String references are not final unless you declare them final.

When your code seems to change a String, it is really constucting a new String object and changing the String reference to point to the new String object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic