File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

== comparison

 
bobby chaurasia
Ranch Hand
Posts: 84
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IN java rule round-up I came across the following question:
Integer a = new Integer(5);
Integer b = new Integer(5);
What is the result of running: if( a == b)
I choose true. On checking the answers the It read as false. Not convinced I compiled the code
public static void main( String args[] ) {
Integer a = new Integer(5);
Integer b = new Integer(5);
if (a == b) {
System.out.println("True");
}
else{
System.out.println("True");
}
On running it printed "true".
Any comments ?
 
Brian Glodde
Ranch Hand
Posts: 171
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The 2nd part of your if/then has a typo. It should be
System.out.println("False");
Then you should see the desired result.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This expression (a == b) compares the addresses in memory of the objects, not a test of equality of state. Since a and b are two distinct objects, a == b is false, as Brian correctly pointed out. If two references point to the same object, however, the result should be true.
The proof of the pudding is in the eating, they say , so:

The output should be:
False
True
Beware of String literals though. Given
String s = "Hello!";
String t = "Hello!";
the String references s and t point to the same object. But
String p = new String("Hello!");
String q = new String("Hello!");
the String references p and q point to different objects!
-anthony
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW if you wish to compare your Integers, use
a.intValue() == b.intValue()
instead.
-anthony
 
Rob Ross
Bartender
Posts: 2205
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or just good old-fashioned equals()...

if (a.equals(b))...
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic