• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

immutable?????????

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12196
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
santosh kothapalli
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Balaji Sampath
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there
Just a doubt.
Does the output for the above code is "321"..
regards
Balaji.S
 
Alejandro Montenegro
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try run it... but yes it gives 321
 
Isha Mackker
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya the output is 321 but what is being asked for is just s1, which is 3 only
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic