| Author |
== comparison
|
bobby chaurasia
Ranch Hand
Joined: Mar 30, 2002
Posts: 84
|
|
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
Joined: Jun 27, 2001
Posts: 171
|
|
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
Joined: Mar 22, 2002
Posts: 1055
|
|
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
Joined: Mar 22, 2002
Posts: 1055
|
|
BTW if you wish to compare your Integers, use a.intValue() == b.intValue() instead. -anthony
|
 |
Rob Ross
Bartender
Joined: Jan 07, 2002
Posts: 2205
|
|
Or just good old-fashioned equals()... if (a.equals(b))...
|
Rob
SCJP 1.4
|
 |
 |
|
|
subject: == comparison
|
|
|