File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When NullPointerException, when "null"?

 
Thomas Markl
Ranch Hand
Posts: 192
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 50
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic