查克没有界限

时间:2013-11-28 23:31:14

标签: java

起初是开个玩笑,但我真的不明白为什么我的程序不会崩溃:

public class ChuckNorris {
    char[] array;

    public boolean HaveBounds(int i)
    {
        System.out.println("Because Chuck Norris knows no bounds.");
        return false;
    }
    public ChuckNorris()
    {
        array = null;
    }

    public char getArrayId(int i)
    {
        return array[i];
    }



}


public class Main {

    public static void main(String[] args) {
        int i = 12;
        ChuckNorris chuckNorris = new ChuckNorris();
        if(chuckNorris.HaveBounds(i))
        {
            char test = chuckNorris.getArrayId(i);
            System.out.println(test);
        }

    }

}

1 个答案:

答案 0 :(得分:5)

因为您返回false

public boolean HaveBounds(int i)
{
    System.out.println("Because Chuck Norris knows no bounds.");
    return false;
}

因此你永远不会达到

char test = chuckNorris.getArrayId(i);

试图访问该数组。

如果它返回true,您将在

的调用中获得NullPointerException
public char getArrayId(int i)
{
    return array[i];
}

因为arraynull