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

Discussion

Which line is an inappropriate use of an assertion?

public class Sample55
{
    private int[] data = new int[4];

    public int at(int i)
    {
        assert i >= 0 && i < data.length : i;
        return data[i];
    }
}

  • A.public int at(int i)
  • B.Every line above is correct as written.
  • C.assert i >= 0 && i < data.length : i;
  • D.private int[] data = new int[4];

Answer: C

at() is public, so the valid index range is part of what callers are promised and must be enforced whether or not -ea is set. Here the check disappears in production and the array access throws ArrayIndexOutOfBoundsException instead. That happens to be a reasonable error, but it is luck rather than design; the bounds belong in an explicit test.

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

Post your comment

Please log in or register to post a comment.