Possible Duplicate:
Basic Java question: String equality
Given
String s= "God";
String k= "God";
Will both s and k be considered to be referring to the same String object? Is there a single instance of String object?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, Java should optimize this so that
s == kto save memory.(The references s and k references to the same object).
Since java do not have pointers, you cannot change the string that s or k points at,
but you can of course change what string that s or k points at. If java would allow pointers,
then a change on what s points as, and the optimization above would have bad consequences.
That is why one should NOT use a string like “LOCK” to lock threads on,
since if third-party jar files does the same, you will BOTH, unknowingly, be using the same object as a thread lock, which might yield very strange and hard-to-find bugs.