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

String

Jian Yi
Ranch Hand

Joined: Feb 01, 2002
Posts: 127
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

Joined: May 05, 2000
Posts: 13974
Because Strings are immutable. 1 doesn't change the String. It creates two brand new Strings! Tricky, huh?


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Jian Yi
Ranch Hand

Joined: Feb 01, 2002
Posts: 127
but strings fname and lname have new values now, don't they?
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
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.


SCJP2. Please Indent your code using UBB Code
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String