1

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?

Community
  • 1
  • 1
user961690
  • 698
  • 1
  • 11
  • 22

2 Answers2

5

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.

Per Alexandersson
  • 2,443
  • 1
  • 22
  • 28
  • 1
    Awesome locking observation. Would never have considered that! – Cory Kendall Sep 25 '11 at 07:34
  • SIR,I used string object as a synchronization object in synchronized block. String object was assigned value everytime new thread was created by taking the value from constructor parameters. So everytime the object instance changed and Synchronization could not be attained. But when the same string value was used,it synchronized the threads This let me conclude that single object instance was created. And that's why I asked this question. You gave me the actual answer to my question. And yes,in Java Programming forum,PROGRAMMERS opine that both Strings may or may not create Single instance. – user961690 Sep 25 '11 at 08:49
1

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.

M Platvoet
  • 1,679
  • 1
  • 10
  • 14