2

Possible Duplicate:
Why Java does not see that Integers are equal?

I have 2 integers that I assign from the same argument.

One of the integers I decrease the value by 1 then increment the value by 1.

When I compare them again they are not always equal.

This is from my book, can someone please explain, I cannot understand my books explanation.

class Test{

    public static void main(String[] args){
        Integer i = Integer.parseInt(args[0]);
        Integer j = i;
        System.out.println("1:" + i + ", j:" + j);
        i--;
        System.out.println("2:" + i + ", j:" + j);
        i++;
        System.out.println("3:" + i + ", j:" + j);
        System.out.println((i==j));

    }
}

Output: Input 256 as argument

1:256, j:256
2:255, j:256
3:256, j:256
false

Thank you for your consideration.

Community
  • 1
  • 1
Quinma
  • 1,436
  • 2
  • 17
  • 39
  • This is both Integer object, which you need to use equals() to compare the value. – nhahtdh Sep 19 '12 at 20:41
  • I understand now, int and Integer are totally different. Thank you for the link Jack Maney, different questions but same answer. Which makes my question not about the increment but really about int vs Integer. – Quinma Sep 19 '12 at 20:43
  • This comes up once a week it seems – Steve Kuo Sep 19 '12 at 21:44

1 Answers1

1

You are comparing two references that are not the same because of the ++-- (New Objects Created). The way to compare two Integer objects equals() method. equals() will check Integer's inner state. Check this code:

    Integer i = 256;
    Integer j=i;
    System.out.println(i==j);         //True  (Because we are pointing the same object)
    i--;
    i++;        
    System.out.println(i==j);         //False (Because reference has changed)
    System.out.println(i.equals(j));  //True  (Because the inner state is the same)
Eli Turchinsky
  • 331
  • 2
  • 8
  • 2
    Btw, if you will compare Integers with values between [-128; 127] you'll still get true. – svz Sep 19 '12 at 20:45
  • Interesting...Do you know why? – Eli Turchinsky Sep 19 '12 at 20:52
  • 1
    My Book reads: To save on memory, Java 'reuses' all the wrapper objects whose values fall in the following ranges: All Boolean values (true and false) All Byte values All Character values from \u0000 to \u007f (i.e. 0 to 127 in decimal) All Short and Integer values from -128 to 127 So ==  will always return true when their primitive values are the same and belong to the above list of values. – Quinma Sep 19 '12 at 20:55
  • 1
    @Eli Turchinsky that is because Integer values of this range are stored in a heap, so if you have `Integer a = 5; Integer b = 5` they will both reference the 5 from this heap. As the references are equal, the `a==b` operation returns `true` – svz Sep 19 '12 at 20:56
  • Nice:-) LISP like implementation (as far as i remember...) – Eli Turchinsky Sep 19 '12 at 21:00