• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Local object reference variables Initialization

 
Swapnil Sonawane
Ranch Hand
Posts: 190
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48934
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 48934
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic