Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2007

Tip: Looking for answers? Try searching our database.

Comparing Integers and Longs

Thread view: 
richnjones@gmail.com - 20 Nov 2007 11:40 GMT
Hello all,

Im a little confused on how number comparison is done. Consider

1    Integer i = new Integer(5);
2    Integer ii = new Integer(5);
3    Long l = new Long(5);
4
5    System.out.println("two Integers " + (i == ii));
6    System.out.println("Integers and Long.intValue " + (i ==
l.intValue()));

The output of this is

two Integers false
Integers and Long.intValue true

The first false I can understand. Using new will create new objects so
that the == will fail. (Correct me if I am wrong). The second output I
expected to be false.

This is how I see things...

1  I have an integer object and a long object
2  Doing l.intValue() will return an int which will be autoboxed up to
an Integer
3  This new Integer I thought would be a new object and so the ==
should fail.

Is the autoboxing being clever and seeing that there is another object
with the same value and just assigning the reference to that? (Like
with Strings)

Why is the second output not false?

TIA

Richard
Chris Dollin - 20 Nov 2007 12:14 GMT
> Hello all,
>
[quoted text clipped - 20 lines]
>
> 1  I have an integer object and a long object

Yes.

> 2  Doing l.intValue() will return an int

Yes.

> which will be autoboxed up to an Integer

No.

No Object is needed; no autoboxing need happen.

Signature

Chris "isn't 'autoboxing' a video game?" Dollin

Hewlett-Packard Limited registered office:                Cain Road, Bracknell,
registered no: 690597 England                                    Berks RG12 1HN

richnjones@gmail.com - 20 Nov 2007 12:24 GMT
Thanks for your reply Chris,

if not autoboxing is happening then the following code should output
true

1  int i  = 5;
2  Integer ii = new Integer(5);
3  System.out.println(i == ii);

which is does :)

Im still not completely clear on how == can be used with primitives.
My understanding is that == checks for object equality (the bit
pattern of the object). Does anyone know how == works with primitives?

TIA
Richard
Andreas Leitgeb - 20 Nov 2007 12:42 GMT
> Im still not completely clear on how == can be used with primitives.

Which is funny, because a lot of java-newbies find it just natural
how primitives are handled, and have problems understanding "=="
for the object-wrappers.

> My understanding is that == checks for object equality (the bit
> pattern of the object). Does anyone know how == works with primitives?

"==" always compares primitive types: either it compares values
(int,long,float,double,byte,short,...), or it compares references,
but it never compares objects!

To compare Objects, you'd use Object's  .equals(other) method, as
overloaded appropriately for any class that you actually use.

PS: in  (Integer == int)-type comparisons, Seemingly it unboxes
 the object, rather than box the primitive.
 You can verify this, by using javap  (or whatever other
 class-file-disassembler) on your sample.class and see what it
 really does.  ...  it calls Integer's intValue() method, and
 does an int-compare. (if_icmpne)

class A {
  public static void main(String[]args){
    Integer i1=new Integer(42);
    int     i2=42;
    System.out.println( (i1 == i2) );
  }
}
Chris Dollin - 20 Nov 2007 13:42 GMT
> Thanks for your reply Chris,
>
[quoted text clipped - 6 lines]
>
> which is does :)

That's not because of autoboxing; that's because of auto/un/boxing
in the special treatment of `==`.

> Im still not completely clear on how == can be used with primitives.

By comparing their values.

> My understanding is that == checks for object equality

No: it compares values, not objects. That is, if its operands are
primitive values, it compares those values; if they are references
(ie a value of class/interface type) then it compares those references;
and if they're mixed, it may apply autounboxing.

> (the bit pattern of the object).

It may come down to that, yes.

> Does anyone know how == works with primitives?

In what sense? It compares their values. How else could it work?

Signature

Chris "rhetorical" Dollin

Hewlett-Packard Limited     Cain Road, Bracknell,                registered no:
registered office:          Berks RG12 1HN                       690597 England

Mark Space - 20 Nov 2007 20:40 GMT
> Thanks for your reply Chris,
>
[quoted text clipped - 10 lines]
> My understanding is that == checks for object equality (the bit
> pattern of the object). Does anyone know how == works with primitives?

Maybe this was mentioned somewhere, though I didn't see it.

Reading line 3, I start with an int i, then see I ==, then I see an
Integer.  If I were a parser, I'd be temped to convert the Integer to
the type of the existing expression (int in this case) first.  Since I
can do that, I'd unbox the Integer to an int and continue.  Hence, ==
will compare two int's and gives true as a result.

I'm not sure, but that's what I speculate.

Try switching i and ii above and see if you get a different result...
Patricia Shanahan - 20 Nov 2007 21:14 GMT
>> Thanks for your reply Chris,
>>
[quoted text clipped - 20 lines]
>
> I'm not sure, but that's what I speculate.

Why speculate, when the JLS tells all? Well, at least quite a lot,
including the answer to this question.

"If the operands of an equality operator are both of numeric type, or
one is of numeric type and the other is convertible (§5.1.8) to numeric
type, binary numeric promotion is performed on the operands (§5.6.2)."

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.1

Patricia
Sabine Dinis Blochberger - 20 Nov 2007 12:15 GMT
> Hello all,
>
[quoted text clipped - 7 lines]
> 6      System.out.println("Integers and Long.intValue " + (i ==
> l.intValue()));

Perhaps Integer.compareTo(Integer anotherInteger) will work.

> The output of this is
>
[quoted text clipped - 4 lines]
> that the == will fail. (Correct me if I am wrong). The second output I
> expected to be false.

Someone will give you a more technical explanation, I'm sure.

> This is how I see things...
>
> 1  I have an integer object and a long object
> 2  Doing l.intValue() will return an int which will be autoboxed up to
> an Integer

Even so, you don't usually compare objects with == but .equals()

> 3  This new Integer I thought would be a new object and so the ==
> should fail.
[quoted text clipped - 8 lines]
>
> Richard

Signature

Sabine Dinis Blochberger

Op3racional
www.op3racional.eu

Patricia Shanahan - 20 Nov 2007 12:46 GMT
...
> 1  I have an integer object and a long object
> 2  Doing l.intValue() will return an int which will be autoboxed up to
> an Integer

There are two ways it could have been designed, the way you described
and by unboxing the Integer to produce an int.

The best place to look to find out which was chosen is the JLS
description of ==. It says "If the operands of an equality operator are
both of numeric type, or one is of numeric type and the other is
convertible (§5.1.8) to numeric type, binary numeric promotion is
performed on the operands (§5.6.2)."

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21

5.1.8 Unboxing Conversion permits Integer to int.

5.6.2 Binary Numeric Promotion says "If any of the operands is of a
reference type, unboxing conversion (§5.1.8) is performed."

I think they made the right choice. A comparison between Integer and int
would be pointless if it were done by boxing the int, but is very useful
if done by unboxing the Integer. It also makes the same conversions
apply to == for mixed types as apply to the binary arithmetic operators.

Patricia
iamrichardjones@googlemail.com - 20 Nov 2007 13:13 GMT
Thanks all! Thats a lot clearer

R
Mike Schilling - 20 Nov 2007 13:46 GMT
> ...
>> 1  I have an integer object and a long object
[quoted text clipped - 19 lines]
> I think they made the right choice. A comparison between Integer and
> int would be pointless if it were done by boxing the int,

I'd say confusing, not pointless.  Assume:

   Integer ii;
   int i;
   i == ii.intValue();

since autoboxing i is done with Integer.valueOf() (not new Integer())  there
would be an implementation-specific range of values for which (i == ii) is
true, but it would be false outside that range.
Patricia Shanahan - 20 Nov 2007 17:11 GMT
>> ...
>>> 1  I have an integer object and a long object
[quoted text clipped - 28 lines]
> would be an implementation-specific range of values for which (i == ii) is
> true, but it would be false outside that range.

You missed out one of the conditions. If ii references an Integer that
was created by new Integer(), the answer would be false even if i is in
the range.

I agree it would be confusing. I suppose it does provide a way to probe
the internals of Integer at run time. I still contend the Java designers
made the right choice.

Patricia


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.