aspose file tools*
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
Author

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;
System.out.println(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
Sheriff

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

Joined: Oct 13, 2005
Posts: 39884
    
  28
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
Rancher

Joined: Aug 05, 2005
Posts: 3739
    
  16
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


Joanne
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Local object reference variables Initialization