-4

Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?
Why is == true for some Integer objects?

class One
{
    public static void main(String[] args) 
    {
           Integer i1 = 10;
           Integer i2 = 10;

        if (i1 == i2) 
        {
            System.out.println("In if ");
        } 
        else
        {
            System.out.println("in else");
        }
    }
}

The output of the above program is In if but if the values of i1 and i2 are changed to 1000 then output is In else.

I know that autoboxing is taking place here but unable to understand the reasons of the output. Thank You!

Community
  • 1
  • 1
Vijay
  • 213
  • 1
  • 9
  • I think it would help alot if you removed all the "enter code here" and fixed the code so we could read it. – warbio Feb 07 '12 at 04:41

3 Answers3

4

== only returns true if both operands refer to the same instance.

In the second case, they return false because they aren't the same instance. (the same reason why you can't compare strings with ==)

But in the first case, the run-time actually caches Integer objects for small values. Thus, i1 and i2 point to the same cached object.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
1

== checks whether two things are the same object;

Normally, when the primitive types are boxed into the wrapper types, the JVM allocates memory and creates a new object. But for some special cases, the JVM reuses the same object.

The following is the list of primitives stored as immutable objects:

  • boolean values true and false

  • All byte values

  • short values between -128 and 127

  • int values between -128 and 127

  • char in the range \u0000 to \u007F

refer http://today.java.net/pub/a/today/2005/03/24/autoboxing.html#immutable_objects

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
0

== is comparing obects (addresses if you like, but not really)

Try

  if (i1.equals(i2))
John3136
  • 28,809
  • 4
  • 51
  • 69