How come you can declare an int[] but not initialize it and if you println it you get null.. however if you change it to a char[] you get a NullPointerException?
That's quite a nice little example. Look at the documentation for PrintStream (the class that System.out is an instance of). You'll see there are lots of overloaded methods for println().
- Which one is called when you pass in an int[]?
- Which one is called when you pass in a char[]?
The difference comes because the two methods process the argument in a different way. And the one taking a char array will throw a NullPointerException (as documented).
Matthew Brown wrote:
Which one is called when you pass in a char[]?
Which one is called when you pass in an int[]?
Thanks for the hint. Saw the oracle docs :
(Q)Which one is called when you pass in a char[]?
public void println(char[] x) Prints an array of characters and then terminate the line. This method behaves as though it invokes print(char[]) and then println().
>>>public void print(char[] s) 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.
Parameters: s - The array of chars to be printed
Throws: NullPointerException - If s is null
(Q)Which one is called when you pass in an int[]?
public void println(Object x) Prints an Object and then terminate the line. 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().
>>>public void print(String s) Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's 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.