char and int array difference

后端 未结 4 1120
傲寒
傲寒 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:15

    System.out is an instance of PrintStream and this class has a few overloaded println methods. In your case:

    1. System.out.println(ch); is using public void println(char x[])
    2. System.out.println(arr); is using public void println(Object x) (there is no public void println(int[] x) method so the closest available type for int[] which println can use is Object).

    The second method is using

    String.valueOf(x);
    

    to get a string representation of the object we want to print and the code of the valueOf method looks like

    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
    

    so it is null-safe (will return the string "null" if the reference holds null).

    The first method is at some level using

    public void write(char cbuf[]) throws IOException {
        write(cbuf, 0, cbuf.length);
                     //    ^^^^^^^ this throws NPE
    }
    

    and because cbuf is null cbuf.length will throw NullPointerException because null doesn't have length (or any other) field.

提交回复
热议问题