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?
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?
Yes, Java should optimize this so that s == k
to 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.
They are the same instance. They are part of the string constant pool. Since strings are considered to be immutable (reflection says otherwise) this is normally no problem at all.