This week's book giveaway is in the General Computing forum.
We're giving away four copies of Emmy in the Key of Code and have Aimee Lucido on-line!
See this thread for details.
Win a copy of Emmy in the Key of Code this week in the General Computing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Paweł Baczyński
  • Piet Souris
  • Vijitha Kumara

Array of objects

 
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.
 
author
Posts: 23843
141
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux 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!!
 
Proudly marching to the beat of a different kettle of fish... while reading this tiny ad
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!