0

Got a weird problem in a UIL CS packet enter image description here
this was the solution

public class equality {
public static void main(String[] args) throws IOException {
    Scanner scan = new Scanner (new File("equality.dat"));
    while (scan.hasNext()) {
        int start = scan.nextInt();
        int step = scan.nextInt();
        int z = start;
        for (int i = 0; i < 5; i++) {
            Integer a = z;
            Integer b = z;
            System.out.printf("%+4d == %+4d is %s\n",a,b,(a==b)); // <-- Confusing part
            z+=step;
        }
        System.out.println();
    }
    scan.close();
}    
}

I was wondering if someone could explain why (a==b) returns true/false. I thought it had to do with the fact that its comparing references and not the value itself but if that was the case, wouldn't they all be false? I'm confused :/

Oscar F
  • 323
  • 2
  • 9
  • 21
  • This has been asked before, so please check out [this link](http://stackoverflow.com/questions/15024933/why-equal-operator-works-for-integer-value-until-128-number) for a pretty decent explanation. – Hovercraft Full Of Eels Nov 15 '14 at 05:25
  • @Hovercraft Full of Eels Thanks! – Oscar F Nov 15 '14 at 05:33
  • You're welcome! The way this works is not intuitively obvious, at least not to me, but it's one of those things you discover after knocking your head against the wall for a while after trying to solve a sneaky bug caused by this set up. – Hovercraft Full Of Eels Nov 15 '14 at 05:34

0 Answers0