aspose file tools*
The moose likes Beginning Java and the fly likes null arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "null arrays" Watch "null arrays" New topic
Author

null arrays

Greg Morphis
Greenhorn

Joined: Apr 01, 2011
Posts: 13
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?

gives you
null
null
but

you get
null
Exception in thread "main" java.lang.NullPointerException
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4490
    
    8

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).
Greg Morphis
Greenhorn

Joined: Apr 01, 2011
Posts: 13
Thanks Matthew! That explains it!
Rahul Sudip Bose
Ranch Hand

Joined: Jan 21, 2011
Posts: 637

To Greg Morphis : Thanks !

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.

Thanks again.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: null arrays