File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Is string immutable? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Is string immutable?" Watch "Is string immutable?" New topic

Is string immutable?

Venkat Ramsimha
Ranch Hand

Joined: Dec 28, 2004
Posts: 127
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);


we know that strings are objects in javacode which are "immutable" that is there value once assigned cannot be 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...
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
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.

Mike Gershman
SCJP 1.4, SCWCD in process
I agree. Here's the link:
subject: Is string immutable?
It's not a secret anymore!