• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String

 
Jian Yi
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From JCHQ:
You have created two strings containing names. Thus
String fname="John";
String lname="String"
How can you go about changing these strings to take new values within the same block of code?
1)
fname="Fred";
lname="Jones";
2)
String fname=new String("Fred");
String lname=new String("Jones");
3)
StringBuffer fname=new StringBuffer(fname);
StringBuffer lname=new StringBuffer(lname);

4) None of the above

Why is the answer 4 not 1?
Thanks,
Jenny
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because Strings are immutable. 1 doesn't change the String. It creates two brand new Strings! Tricky, huh?
 
Jian Yi
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but strings fname and lname have new values now, don't they?
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String objects are not changed. They are not referenced anymore from the references. The two references point to new String objects. The question could have been better worded.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic