3

I found a lot of questions about comparing objects in Java. Primitive types we can compare using == for example int

    int i1 = 0;
    int i2 = 0;
    int i3 = 1000;
    int i4 = 1000;
    int i5 = 1;
    int i6 = 2;

    System.out.println(i1 == i2);
    System.out.println(i3 == i4);
    System.out.println(i5 == i6);

output is

true
true
false

When we want to compare Integer objects we can do it in two ways

equals()

and here we are comparing values

    Integer i1 = 0;
    Integer i2 = 0;
    Integer i3 = 1000;
    Integer i4 = 1000;
    Integer i5 = 1;
    Integer i6 = 2;

    System.out.println(i1.equals(i2));
    System.out.println(i3.equals(i4));
    System.out.println(i5.equals(i6));

output is

true
true
false

or we can use == which compares references.

Let's take two String variables with the same value

    String s1 = "Yes, this is dog";
    String s2 = "Yes, this is dog";

    System.out.println(s1 == s2);
    System.out.println(s1.equals(s2));

It is well-known that results of both comparisons will be true

true
true

So now, I want to do this same with Integer objects. I run this piece of code

    Integer i1 = 0;
    Integer i2 = 0;
    Integer i3 = 1000;
    Integer i4 = 1000;
    Integer i5 = 1;
    Integer i6 = 2;

    System.out.println(i1 == i2);
    System.out.println(i3 == i4);
    System.out.println(i5 == i6);

and the output is

true
false
false

We can meet this kind of behavior for Integer objects with these values: [-128,127]

    for (int i = -129;i <129;i++) {
        Integer i1 = i;
        Integer i2 = i;
        System.out.println(i1 == i2);
    }

output:

false
true
...
false

I would like to know, what is the reason of this behavior? Does it have a big influence to performance?

In which package and in which class can I find a piece of code which takes care of this situation?

In which Java version it has been introduced and is it be maintained in Java 8?

If I want to change this behaviour, am I able to do that or I should use operator new each time?

Integer i = new Integer(1024);

Thank you in advance

ruhungry
  • 4,506
  • 20
  • 54
  • 98

0 Answers0