This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Is string immutable?" Watch "Is string immutable?" New topic
Author

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);
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

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: http://aspose.com/file-tools
 
subject: Is string immutable?
 
Similar Threads
some queries in the program
why doesn't this work?
Regex.
private constructor
Thanks anyway