aspose file tools*
The moose likes Beginning Java and the fly likes == string comparison Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "== string comparison" Watch "== string comparison" New topic
Author

== string comparison

Antony Isaac
Greenhorn

Joined: Dec 10, 2009
Posts: 4
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

Joined: Jan 10, 2002
Posts: 61206
    
  66

== 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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38821
    
  23
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

Joined: Dec 10, 2009
Posts: 4
Thanks for the replies.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38821
    
  23
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: == string comparison