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

Discussion

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

public class Fragment42
{
    private static int half(int n)
    {
        assert n % 2 == 0 : n;
        return n / 2;
    }

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

  • A.Compilation fails.
  • B.4, then an AssertionError with message 7
  • C.The program prints 4 and 3
  • D.An AssertionError with message 8

Answer: B

half(8) satisfies the precondition and prints 4. half(7) violates it, so the assertion throws before the division and 3 is never printed. Checking a precondition of a private method is precisely the use the Oracle guide endorses, in contrast to argument checking in public methods.

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

Post your comment

Please log in or register to post a comment.