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

Discussion

Which line is an inappropriate use of an assertion?

public class Sample12
{
    static int served = 0;

    static boolean serve()
    {
        served++;
        return true;
    }

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

  • A.served++;
  • B.System.out.println(served);
  • C.All of these assertions are appropriate.
  • D.assert serve();

Answer: D

serve() changes state that outlives the assertion, so the program prints 1 with -ea and 0 without it. An expression inside an assert must be free of side effects precisely so that enabling or disabling assertions cannot change what the program does.

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

Post your comment

Please log in or register to post a comment.