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

Discussion

Which line rests on a mistaken assumption?

public class Sample64
{
    public static void main(String[] args)
    {
        assert sum() == 3;
        System.out.println(sum(1, 2));
    }

    static int sum(int... parts)
    {
        assert parts != null;
        int t = 0;
        for (int p : parts) t += p;
        return t;
    }
}

  • A.assert parts != null;
  • B.System.out.println(sum(1, 2));
  • C.The code is correct as it stands.
  • D.assert sum() == 3;

Answer: D

Calling a varargs method with no arguments passes an empty array, so sum() returns 0 and the assertion claiming 3 is false. The null check inside the method is redundant rather than wrong, since the array is never null. The error is the expectation in the caller.

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

Post your comment

Please log in or register to post a comment.