File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes When NullPointerException, when Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When NullPointerException, when "null"?" Watch "When NullPointerException, when "null"?" New topic
Author

When NullPointerException, when "null"?

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
Hello,
I have got a question regarding „NullPointerException“ – when does it occur?
Why does it print „null“ when I print out String s which has no reference
Why does it print „NullPointerException“ when i perform an operation on
String/Object s which has no reference?

Ronald Schindler
Ranch Hand

Joined: Jul 11, 2000
Posts: 50
I'll take a crack at this. String objects initialize to null unless you specify what it points at such as:
String s = "mystring";
As for the NullPointer - the operation is trying to perform an operation on an object which in this case has been initalized to null.
Let me know if that doesn't help.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
The member s is a reference to a String instance. s is initialized to the value null. The method System.out.println sees that s has the value null and kindly prints the string "null". It would do the same for any type of reference which has the null value.
However, when you do s.getLength() you are saying "send the getLength() message to the object referenced by s." But s does not refer to any object and so you get the NullPointerException. This name obviously comes from Java's C/C++ origins. Maybe it should have been better called "NullReferenceException".
That's how I see it.
-Barry


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When NullPointerException, when "null"?