-1

Each time I run the code, I get different sequence of Output. Please help me out.. Why this is happening?

public class Hello {
    public static abstract class b {
        b() {
            System.out.println("Abstract Class Constructor");
        }

        public abstract void display();
    }

    public static class d extends b {
        d() {
            System.out.println("Subclass Constructor");
        }

        public void display() {
            System.out.println("Function Over-Ridden");
            throw new ArithmeticException("Division by Zero");
        }
    }
    public static void main(String[] args){
        d a=new d();
        a.display();
    }
}
Shekhar Rai
  • 2,008
  • 2
  • 22
  • 25
  • 2
    can you post your output? – Jarlik Stepsto Mar 05 '17 at 10:57
  • Exception in thread "main" java.lang.ArithmeticException: Division by Zero at Suyash.Hello$d.display(Hello.java:22) Abstract Class Constructor at Suyash.Hello.main(Hello.java:27) Subclass Constructor Function Over-Ridden – Suyash Jain Mar 05 '17 at 12:26

2 Answers2

4

The sequence of the output is always :

Abstract Class Constructor
Subclass Constructor
Function Over-Ridden
Exception in thread "main" java.lang.ArithmeticException: Division by Zero

However, the first 3 are written to standard output, while the last one is written to standard error. The output of those two streams is interleaved in your console window, which makes it look like the order is different in different runs.

If you change your System.out.println statements to System.err.println, all the outputs will be written to the same stream and will always be displayed in the same order.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • What is the reason for interleaving in console window? – Suyash Jain Mar 05 '17 at 12:21
  • @SuyashJain That's an implementation detail of the JVM. One possible explanation would be that the writing of the output and error streams to the console may be performed by separate threads. – Eran Mar 05 '17 at 12:26
0

The problem is, that your println writes to the standard output, but when you throw an exception, it is dumped into the error output. Usually when you mix these two streams, the lines can get mixed up between the two.

You can change your println to use the error stream to prevent this mixup:

System.err.println("..."); //notice the err part
Nulano
  • 1,148
  • 13
  • 27