Given:

public class Test3 {

    public static void main(String[] args) {
        String names[] = new String[3];
        names[0] = "Mary Brown";
        names[1] = "Nancy Red";
        names[2] = "Jessy Orange";
        try {
            for (String n : names) {
                try {
                    String pwd = n.substring(0, 3) + n.substring(6, 10);
                    System.out.println(pwd);
                } catch (StringIndexOutOfBoundsException sie) {
                    System.out.println("String out of limits");
                }
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array out of limits");
        }
    }
}

What is the result?

A.

Marrown
String out of limits
JesOran

B.

Marrown
String out of limits
Array out of limits

C.

Marrown
String out of limits

D.

Marrown
NanRed
JesOran

题解

names[0] 的长度是 10,索引范围是 0~9;names[1] 的长度是 9,索引范围是 0~8;names[2] 的长度是 12,索引范围是 0~11。当字符串索引范围不正确的时候会抛出「StringIndexOutOfBoundsException」例外。

程序第 11 行有用到字符串对象的「substring」方法来取得子字符串,取得 names 字符串数组中每个字符串的子字符串,子字符串的字符索引范围是 0~2 和 6~9,所以长度未满 10 的 names[1] 将会抛出「StringIndexOutOfBoundsException」例外,而其他的字符串则可以成功地进行子字符串的串接。