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 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 "immutable?????????" Watch "immutable?????????" New topic


Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 481
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;
bibby young

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

Joined: Oct 02, 2003
Posts: 11955

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

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;

Try this and see ur doubt will be cleared as what immuteable means.

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"..
Alejandro Montenegro

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

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:
subject: immutable?????????
It's not a secret anymore!