aspose file tools*
The moose likes Java in General and the fly likes comparison Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "comparison" Watch "comparison" New topic
Author

comparison

Ela Jha
Greenhorn

Joined: Jul 17, 2006
Posts: 12
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

Joined: Apr 21, 2006
Posts: 1847
never compare object instances using the == operator. It's not going to work.


42
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

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 ]

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Brian Mozhdehi
Ranch Hand

Joined: Aug 17, 2006
Posts: 81
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

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ela Jha
Greenhorn

Joined: Jul 17, 2006
Posts: 12
Thank you all for the answers
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: comparison