File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Strange Behaviour Of Wrapper Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic

Strange Behaviour Of Wrapper Class

Sanket Meghani

Joined: Jan 15, 2007
Posts: 14
Hello EveryOne,

I was just playing around the wrapper classes and observed some unexpected behaviour.

public class HelloWorld
public static void main( String args[] )
Integer i1 = 100;
Integer i2 = 100;

System.out.println( "i1 == i2 : " + ( i1 == i2 ) );

Output of the above code is unexpected with different values of i1 and i2.

For the current values ( i1 = 100 and i2 = 100 ) the output is : "i1 == i2 : true"

But for the following code,

public class HelloWorld
public static void main( String args[] )
Integer i1 = 1000;
Integer i2 = 1000;

System.out.println( "i1 == i2 : " + ( i1 == i2 ) );

the output is "i1 == i2 : false"

From different conbinations I have observed that in the above code for values of i1 and i2 between -128 to 127 ( range of byte ), i1 == i2 evaluates to true and for other values i1 == i2 evaluates to false.

What could be the reason behind this behaviour?

Thank You,
Sanket Meghani.
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
Check out this post.

Specifically the discussion that follows on from the first paragraph in Ken Blair's first post.
[ August 03, 2007: Message edited by: Joanne Neal ]

Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Cross-post. Also posted in Advanced, and answered there (initially by me).

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
I agree. Here's the link:
subject: Strange Behaviour Of Wrapper Class
It's not a secret anymore!