This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "equals()" Watch "equals()" New topic
Author

equals()

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1368
Float value1 = new Float(12);
Float value2 = new Float(12);

value1.equals(value2) returns true / false? (equals compares only String contents)
value1 == value2 returns true / false ? ( == compares object references)
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Are you asking? What happens when you run it?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36478
    
  16
What have you tried? Have you looked in the Java™ Language Specification about caching values? Did you see whether that applies to Float? Is there any evidence that th Float has a String in it anywhere?
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2771
    
  10

== compares references and equals() compares values. If you don't understand the difference between references and values, then learning that is your first job. While it's possible to code in Java without clearly understanding references, I don't think it's really possible to do it well.

Somewhat complicating the issue is that the default implementation of equals() just compares references, so it does exactly what == does. However, Integers override that behavior, and instead compare the integer values, so even two Integer objects with different references will be equal according to equals() if they contain the same value.

Further complicating the issue is that Java's compiler tries to optimize memory usage. It will sometimes recognize that two Integers contain the same value and so can share a reference. In those cases, the == test will return true even though it seems you are comparing two different objects. It is because Integers are immutable that the compiler can safely make this optimization.



 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: equals()
 
Similar Threads
wrapper class
Implementing scanner into a simple login page
netbeans 7.1 errors
why equals methods printing false ?
IF Else Error. Why?