0

Following is what I have written. Line 5 and line and line 8 should be same as

true

but they are different. I am not able to figure out what is actually happening. Help

public static void main(String[] args)
    {
        Integer i1 = 127;

        Integer i2 = 127;

        System.out.println(i1 == i2);  //Shows true 

        Integer i3 = 128;

        Integer i4 = 128;

        System.out.println(i3 == i4);  // shows false
    }
Markus Pscheidt
  • 6,853
  • 5
  • 55
  • 76
  • 2
    Take a look at http://stackoverflow.com/a/20948389/1369579 or http://stackoverflow.com/a/3130348/1369579 – Dorian Sep 13 '16 at 06:52
  • 1
    Good spot and good question, despite being a duplicate. One of the most pernicious parts of Java, in my opinion. The duplicates explain the reasons. – Bathsheba Sep 13 '16 at 06:53
  • `i3 == i4` compares the _objects_, not the _values_. Use `i3.intValue() == i4.intValue()` if you want to compare the values. – Tim Biegeleisen Sep 13 '16 at 06:53
  • Or you can ace it with `i3.intValue() == i4`. – Bathsheba Sep 13 '16 at 06:53
  • @Bathsheba Also `(int) i3 == i4` – Marko Topolnik Sep 13 '16 at 06:55
  • 1
    Note that `i3 == i4` *can* be true. The documentation requires `Integer.valueOf` to cache the results for -128..127, but does not forbid caching other values. It depends upon the implementation you are using. – Andy Turner Sep 13 '16 at 07:00
  • See also this http://codegolf.stackexchange.com/questions/28786/write-a-program-that-makes-2-2-5/28818#28818 where you can manipulate the cache to make the comparisons say anything you want. And they claim Java is a "secure" language. – Bathsheba Sep 13 '16 at 07:04

0 Answers0