Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== string comparison

 
Antony Isaac
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I read that string comparison using == should not be done, however when I use it in code it seems to work. Is this something that was changed in recent versions of Java? For example the following works and prints true. If I change one value it returns false. The Netbeans IDE does give me the warning "comparing string with ==", and I do understand the logic on comparing object references etc. Appreciate your response.

Tony

class Person {

String s1 = "tony";
String s2 = "tony";

void doSomething() {
System.out.println((s1 == s2));
}
}
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64631
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== is not a check for equality, but a check for identity. It only happens to work in the case you show because you are comparing the same instance from the literal string pool to itself.
 
Campbell Ritchie
Sheriff
Posts: 48424
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
to elaborate on what Bear said: any Strings which are compile-time constants (see the index to the Java™ Language Specification) are put into a pool; if the same compile-time constant String is used again, the same object is used. Then == will work.
Have you seen what it says in the String documentation about "can be safely shared"? That is something similar; the Strings are here being shared.
Try this:Execute with
 
Antony Isaac
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies.
 
Campbell Ritchie
Sheriff
Posts: 48424
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic