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

Discussion

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

public class Sample25
{
    static int count = 0;

    static boolean bump() { count++; return true; }

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

  • A.The program prints 0
  • B.An AssertionError is thrown.
  • C.Compilation fails.
  • D.The program prints 1

Answer: A

bump() is only called if the assertion is evaluated, and without -ea it is not. count stays 0. The same source prints 1 under -ea, so the program's observable behaviour depends on a debugging flag. The Oracle guide names this as the mistake to avoid: assertions must be free of side effects.

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

Post your comment

Please log in or register to post a comment.