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

Discussion

Which line is an inappropriate use of an assertion?

public class Sample25
{
    public static void main(String[] args)
    {
        int i = 0;
        while (i < 3)
        {
            assert i++ < 3;
        }
        System.out.println(i);
    }
}

  • A.assert i++ < 3;
  • B.while (i < 3)
  • C.System.out.println(i);
  • D.Nothing here is wrong.

Answer: A

The loop's only increment lives inside the assertion, so without -ea nothing advances i and the while loop never ends. With assertions enabled it terminates and prints 3; disabled, the program hangs. A loop variable must never be advanced inside an assert.

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

Post your comment

Please log in or register to post a comment.