aspose file tools*
The moose likes Ranch Office and the fly likes error in roundup? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » This Site » Ranch Office
Bookmark "error in roundup?" Watch "error in roundup?" New topic
Author

error in roundup?

jaco hoff
Greenhorn

Joined: Apr 21, 2007
Posts: 2
I think I may have found an error in the cow roundup. I forgot the question number though, so I can't look it up again. The question was if 2 Integers with value 5 are '=='. The correct answer is yes. Shorts and Integers with a value between -128 and 127 are considered '==', even if they are different objects. With another value they are not '==', but are 'equals'. (Not good English, but I think you know what I mean).
Can someone please confirm if that question was incorrect?
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 31079
    
163

Jaco,
Welcome to JavaRanch!

The roundup was written before Java 5 came out. Java 5 introduced generics where the behavior you describe was introduced. Before that, comparing two Integers was like comparing two Objects - where you had to use equals().

There was a discussion in this forum recently about upgrading the roundup for Java 1.4. I don't recall the outcome.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I'm quite sure (without having really tried it) that

new Integer(5) != new Integer(5)

even in Java 5, *but*

Integer.valueOf(5) == Integer.valueOf(5)

That is, the valueOf method (which is also used by autoboxing) does the caching. The constructor simply can't, technically - two calls *have* to create two distinct objects.


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
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 31079
    
163

Originally posted by Ilja Preuss:
I'm quite sure (without having really tried it) that ...

For what it's worth, I just tried it. You are correct.
jaco hoff
Greenhorn

Joined: Apr 21, 2007
Posts: 2
so
Integer i1 = 5;
Integer i2 = 5;
System.out.println(i1 == i2);
returns true.
and

Integer i1 = new Integer(5);
Integer i2 = new Integer(5);
System.out.println(i1 == i2);
returns false.

Nasty little details. Thanks for the replies
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: error in roundup?