Why equal operator works for Integer value until 1

2019-01-03 03:15发布

Why Integer "=" operator does not work for 128 and after Integer values? Can someone explain this situation?

This is my Java environment: java version "1.6.0_37"

Java(TM) SE Runtime Environment (build 1.6.0_37-b06)

Java HotSpot(TM) 64-Bit Server VM (build 20.12-b01, mixed mode)

Sample Code:

    Integer a;
    Integer b;
    a = 129;
    b = 129;

    for (int i = 0; i < 200; i++) {
        a = i;
        b = i;

        if (a != b) {
            System.out.println("Value:"+ i + " - Different values");
        } else {
            System.out.println("Value"+ i + " Same values");
        }
    }

Some part of console output :

Value:124 - Same values
Value:125 - Same values
Value:126 - Same values
Value:127 - Same values
Value:128 - Different values
Value:129 - Different values
Value:130 - Different values
Value:131 - Different values
Value:132 - Different values

Thanks!

7条回答
【Aperson】
2楼-- · 2019-01-03 03:57

Depending on how you get your Integer instances, it may not work for any value:

System.out.println(new Integer(1) == new Integer(1));

prints

false

This is because the == operator applied to reference-typed operands has nothing to do with the value those operands represent.

查看更多
登录 后发表回答