char and int array difference

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

    You are actually calling two separate, overloaded System.out.println() methods. public void println(char[] x) is overloaded as per the documentation. No specific overloading of println(Object x) exists for the int[] arrays.

    So, when println() is called on an integer array, public void println(Object x) is called. According to the Javadocs:

    This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

    Since the value of the string is null, the method prints null.

    The println() method works somewhat differently when it takes a character array as a parameter. Superficially, the method itself seems similar:

    Prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println().

    However, the print(char[]) method behaves quite differently in key ways:

    Prints an array of characters. The characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

    Thus, it calls a different method. The documentation for print(char[]) explicitly states that in your situation, your exception is thrown:

    Throws: NullPointerException - If [input parameter] s is null

    Hence, the cause of the difference in behavior.

    See Javadocs for more information about the println and print methods: http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println()

提交回复
热议问题