-2

Hi I'm getting varying results depending on the value of these two Integer wrapper objects.

public class Program{

    public static void main(String []args){

        Integer i3;
        Integer i4;

        for(int i=-200; i<200; i++)
        {
            i3 = i;
            i4 = i;

            System.out.print(i + " : ");

            if(i3==i4)
            {
                System.out.print("Same object. ");
            }
            if(i3.equals(i4))
            {
                System.out.println("Meaningfully equal");
            }
        }
     }
}

If the values for i3 and i4 are between -128 and 127, both conditions are true. But outside this range, i3==i4 is no longer true. I guess it has something to do with the bit pattern and the fact that you need more than 8 bits to represent 128?

jimbo123
  • 289
  • 3
  • 7
  • 13

1 Answers1

0

Integers can be compared with == in range from -128 to 127

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63