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

Array of objects

Cathy Song
Ranch Hand

Joined: Jul 01, 2003
Posts: 92
Consider this program:
class ArrayObj{
public static void main (String[] args) {
String[] array = new String[5];
System.out.println(array[0]); //line 1
System.out.println(array[0].toString()); //line2-nullPointerException
}
}

Why does line 1 print null and line 2 generate an exception?
I was expecting line 1 to throw a nullPointerexception also, since I thought
toString() method would be called implicitly.

Thanks,
Cathy.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18117
    
  39

Originally posted by Cathy Song:

Why does line 1 print null and line 2 generate an exception?
I was expecting line 1 to throw a nullPointerexception also, since I thought
toString() method would be called implicitly.

Thanks,
Cathy.


Line 1 print "null" because the printstream class checks for null before printing the string... Here is the relevant entry from the Java Docs:

Print 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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Cathy Song
Ranch Hand

Joined: Jul 01, 2003
Posts: 92
Ah thanks soooooooooo much!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array of objects
 
Similar Threads
Array and toString() Method
NullPointerException
Three dim array
Strange behavior of length variable
toString() and null