Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

comparison

 
Ela Jha
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer i= new Integer("10");
if (i.toString() == i.toString())
System.out.println("Equal");
else
System.out.println("Not Equal");

it prints Not Equal,can anyone explain me why?
 
Jeroen T Wenting
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
never compare object instances using the == operator. It's not going to work.
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The == operator returns true if both variables point to the same object.

When comparing strings this may or may not be the case.
The JVM pools strings with the same value which sometimes causes == to return true.

To compare strings use the String.equals(String) method.
java.lang.Object)" target="_blank" rel="nofollow">http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#equals(java.lang.Object)
[ August 20, 2006: Message edited by: Ben Souther ]
 
Brian Mozhdehi
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FYI, the arsenal of methods for doing this allows you also to do MyString.equalsIgnoreCase(anotherString) which is similar to equals, except it ignores case, obviously

Also, (MyString.compareTo(anotherString) == 0) or
(MyString.compareToIgnoreCase(anotherString) == 0).

For non-ascii Strings, you should not use any of the above and instead use a Collator, which is found in the java.text package.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Brian Mozhdehi:

For non-ascii Strings, you should not use any of the above and instead use a Collator, which is found in the java.text package.


All Strings in Java are unicode strings. Collators are good for strings with Locale-specific characters. That has less todo with different technical encodings, but more with different sorting habits in different languages and cultures.
 
Ela Jha
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all for the answers
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic