File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Local object reference variables Initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Local object reference variables Initialization" Watch "Local object reference variables Initialization" New topic

Local object reference variables Initialization

Swapnil Sonawane
Ranch Hand

Joined: Jan 02, 2008
Posts: 190
I have a doubt regarding initialization of local object reference variables.

According to the book "Programmer's guide to Java Certification" page no 75

public static void main(String args[])
String importantMessage;

It gives a compiler error. And rightly so.

But as the book says,
If the variable importantMessage is set to null, the program will compile. However, at runtime, a NullPointerException will be thrown since the variable importantMessage will not denote any object.

I tried the statement String importantMessage=null and String importantMessage="" both inside the main. They do not cause any runtime exception.

Please explain.

Swapnil S. Sonawane<br /> <br />B.Tech (Expected May 2009)<br />Computer Science, NIT Durgapur, India<br />SCJA 1.0
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45271
I would expect you to get an output rather like "Message = null". I wouldn't expect a runtime Exception to be thrown.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45271
If you use "importantMessage = "";" you are setting it to the empty String, which a String which has nothing in, but is still a bona fide object. So it prints out nothing and runs happily.

If you pass null to a println() call, it finds the null and prints the word null.
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
If that is the complete code from the book then the book is wrong, because (as Campbell says) println() accepts a null argument.
However, if there is more code that you have not included, and that code includes calls to String methods using the 'importantMessage' reference variable, then you will get a NullPointerException
e.g. the following would throw a NPE

I agree. Here's the link:
subject: Local object reference variables Initialization
It's not a secret anymore!