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

Discussion

The program is run with java -ea Fragment102 - what will be the output?

public class Fragment102
{
    public static void main(String[] args)
    {
        assert "abc".charAt(3) == 0;
        System.out.println("done");
    }
}

  • A.The program prints done
  • B.A StringIndexOutOfBoundsException is thrown.
  • C.An AssertionError is thrown.
  • D.Compilation fails.

Answer: B

Valid indices run from 0 to length minus one, so index 3 is out of range for a three-character string and charAt throws while the condition is being evaluated. The exception replaces any assertion outcome. Unlike substring, charAt does not accept an index equal to the length.

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

Post your comment

Please log in or register to post a comment.