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

Discussion

Which line contains the error?

public class Sample60
{
    interface Op { int apply(int v); }

    public static void main(String[] args)
    {
        Op twice = v ->
        {
            assert v >= 0 : v;
            return v * 2;
        };
        System.out.println(twice.apply(-3));
    }
}

  • A.assert v >= 0 : v;
  • B.interface Op { int apply(int v); }
  • C.The code is correct as it stands.
  • D.System.out.println(twice.apply(-3));

Answer: D

Assertions are perfectly legal inside a lambda body, and this one states a reasonable precondition. The error is the call, which passes -3 and so breaks the stated invariant. With -ea it reports an AssertionError carrying -3; without it the method quietly returns -6.

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

Post your comment

Please log in or register to post a comment.