Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array of objects

 
Cathy Song
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21115
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Cathy Song
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah thanks soooooooooo much!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic