aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes 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 "immutable?????????" Watch "immutable?????????" New topic
Author

immutable?????????

Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 479
we know that strings are immutable.

then how come in the following code s1 prints 3

public class Test
{

public static void main (String[] args)
{
String s1 = "1";
String s2 = "2";
String s3 = s1;
s1="3";
System.out.println(s1+s2+s3);/////
}
}
bibby young
Greenhorn

Joined: Aug 05, 2005
Posts: 4
Strings are immutable,but what we're talking about here is the String object. s1 is a reference,and can obviously point to any String object.


坚持就是胜利!
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10908
    
  12

What you are doing here is telling the JVM to create a brand new string "3", and change s3 to refer to it. the original string that s3 USED to refer to hasn't changed... if you print s1, it'll still print "1".

in other words, you can chage what string a reference points to, you can create new string, but you CAN'T change an old string.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
santosh kothapalli
Greenhorn

Joined: Dec 27, 2005
Posts: 26
public class TimDig extends TimDigSuper{
//String device = "Mobile.device";
public static void main(String[] args) {
String s1 = new String("D");
String s2 = "2";
String s3 = s1;
s1.toLowerCase();
System.out.println(s1+s2+s3);/////
}


}
Try this and see ur doubt will be cleared as what immuteable means.
cheers,
Santu.


Santosh K<br />SCJP 1.4,SCWCD
Balaji Sampath
Ranch Hand

Joined: Sep 30, 2005
Posts: 63
Hi there
Just a doubt.
Does the output for the above code is "321"..
regards
Balaji.S
Alejandro Montenegro
Greenhorn

Joined: Jul 05, 2004
Posts: 29
try run it... but yes it gives 321
Isha Mackker
Greenhorn

Joined: Oct 18, 2005
Posts: 29
Ya the output is 321 but what is being asked for is just s1, which is 3 only
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: immutable?????????
 
Similar Threads
String is immutable object but??
String
please help me
How many String object created?
Question on Strings and String pool