char and int array difference

后端 未结 4 1127
傲寒
傲寒 2021-02-18 22:23

When I try to print the uninitialized static char array it gives run time error (Null pointer exception) whereas the uninitialized static int array

4条回答
  •  我寻月下人不归
    2021-02-18 23:01

    The answer exists in the PrintWriter source code (of which System.out is an instance).

    Start with the fact that the uninitialized arrays, as reference variables, are given the default of null.

    The println(char[]) (eventually) attempts to call .length on the passed in array. It's null, resulting in the NullPointerException. println(char[]) (eventually) calls write(char[]):

    public void write(char buf[]) {
        write(buf, 0, buf.length);
    }
    

    There is no overload of println matching int[], but there is a println(Object). There it (eventually) attempts String.valueOf, passing the null reference, so String.valueOf takes the null and returns the String "null". println(Object) calls print(Object):

    public void print(Object obj) {
        write(String.valueOf(obj));
    }
    

提交回复
热议问题