This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes == and equals()  Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "== and equals()  " Watch "== and equals()  " New topic
Author

== and equals()

adam Lui
Ranch Hand

Joined: Sep 03, 2007
Posts: 186
Integer x = new Integer (22);
Integer y = new Integer (22);
if(x == y) System.out.println ("x == y is true"); else System.out.println ("x==y is false");
if(x.equals(y)){System.out.println ("x.equals(y) is true");} else System.out.println ("x.equals(y) is false");

the output is
---------- Capture Output ----------
x==y is false
x.equals(y) is true
> Terminated with exit code 0.

I doubt about x and y have the same value, why it turns out false?
x and y is true, because they share the same data type, or based on same value 22?


boolean b = true;<br />System.out.println ("I believe in Java.<br />Java will make my dream come " + b);
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

== is a simple comparison of values. For primitives, this is straight forward. For references, it compares whether the same object is referenced.

When you create instances using "new," you are creating distinct objects. Even if two instances might be considered "equal" according to how their equals method is implemented, they are separate objects and == will indicate this.
[ September 18, 2007: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
 
subject: == and equals()
 
Similar Threads
Khalid question on .equals()
comparison doubt - K&B book
equals() and ==, doubt
hashCode and equals
Can anyone explain what is == and equal( ) ?