Invalid output for integer comparison values

I have the following code.

public static void doIntCompareProcess() {
    int a = 100;
    int b = 100;

    Integer c = 200;
    Integer d = 200;

    int f = 20000;
    int e = 20000;

    System.out.println(c == d);
    compareInt(e, f);
    compareInt(a, b);
}

public static void compareInt(Integer v1, Integer v2) {
    System.out.println(v1 == v2);
}

This gives me this result:

false
false
true

If the output should be:

false
false
false

Why am I getting the wrong output for the code?

+3
source share
2 answers

The last line corresponds to:

compareInt(100, 100);

Since it compareInt()takes two objects Integer, two parameters receive an automatic box. During this process, instances Integer(n)for small values nbecome interned. In other words, compareInt()gets two references to the same object Integer(100). This is what makes the last comparison evaluate to true.

See the == operator in Java for a comparison of wrapper objects.

== Integer. . fooobar.com/questions/3982/...

+11

-128 127 . 100 - , . , , , , Integer. , , 100 , compareInt() , , true.

+3

All Articles