Machine-translated by Google. Questions are authored in English.
Top

Discussion

The program is run with java -ea Snippet40 - what will be the output?

public class Snippet40
{
    static int x;

    static
    {
        x = 5;
        assert x > 10 : "x is " + x;
    }

    public static void main(String[] args)
    {
        System.out.println(x);
    }
}

  • A.An AssertionError is thrown directly.
  • B.Compilation fails.
  • C.The program prints 5
  • D.An ExceptionInInitializerError caused by an AssertionError.

Answer: D

Assertions are legal in a static initialiser. This one fails while the class is being initialised, and any Throwable that escapes static initialisation other than an Error is wrapped, while an Error propagates as ExceptionInInitializerError reporting the AssertionError as its cause. main never runs.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.