Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compiler integer bug [duplicate]

Tags:

java

I have this code that appeared in a quiz

public class Main {
  public static void main(String[] args) {
    class b {
      int i = 32;
      b() { b(); }
      void b() { System.out.println(++i); }
    }

    class d extends b {
      int i = 8;
      d() {}
      void b() { System.out.println(--i); }
    }

    b b = new d();
  }
}

What should be the output? It turns out that the answer is -1 while I expected it to be 7. Is java broken?

like image 228
Andreas Avatar asked May 10 '26 07:05

Andreas


1 Answers

Let us walk through the order of execution:

  1. Before new d() creates an object of d, it needs to invoke super().
  2. Control is transferred to the default constructor of b.
  3. Constructor of class b will invoke the method b but since there is an overridden method available in class d, it will be invoked.
  4. Note that the instance of b is not yet created and the value of i is hidden (d.i hides b.i) and hence the value of i is 0. So doing --i generates -1 as the output.
like image 194
Aniket Sahrawat Avatar answered May 11 '26 22:05

Aniket Sahrawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!