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

Discussion

Which line contains the error?

public class Sample41
{
    public static void main(String[] args)
    {
        assert "abc".substring(3).isEmpty();
        assert "abc".charAt(3) == 'd';
        System.out.println("checked");
    }
}

  • A.assert "abc".charAt(3) == 'd';
  • B.assert "abc".substring(3).isEmpty();
  • C.System.out.println("checked");
  • D.Nothing here is wrong.

Answer: A

The two look symmetrical but are not. A start index equal to the length is legal for substring and gives the empty string, so the first assertion passes. charAt rejects an index equal to the length and throws StringIndexOutOfBoundsException, so the second fails before it can be evaluated as true or false.

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

Post your comment

Please log in or register to post a comment.