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

Discussion

Which line stops working when the program is run without -ea?

public class Sample15
{
    static int cursor = 0;

    public static void main(String[] args)
    {
        int[] data = {10, 20, 30};
        assert data[cursor++] == 10;
        System.out.println(cursor);
    }
}

  • A.System.out.println(cursor);
  • B.The output is the same either way.
  • C.assert data[cursor++] == 10;
  • D.int[] data = {10, 20, 30};

Answer: C

The increment is inside the assertion, so cursor advances only when assertions are enabled: the program prints 1 with -ea and 0 without. Any counter, iterator or index the program later depends on must be moved outside the assert.

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

Post your comment

Please log in or register to post a comment.