• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullPointers in Java

 
nandkishor rao
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does a string variable throws NullPointerException if we try to access
if not then why? Is it because it implements toString()?
 
Krishna Rao
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nandakishore,
String throws Nullpointerexception for sure if it is null.

String s = null;
System.out.println(s.toString());
Gives: Exception in thread "main" java.lang.NullPointerException

Hope this helps
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The String class has nothing to do with it.

The variable holds a reference to an object. If the reference is null and you try to call a method using it, you get a NullPointerException. That is true always, regardless of the class of object to which the variable is declared to refer.

Unlike other languages (e.g. C++), Java cannot have variables that hold an object. They always hold a reference to an object, or they hold a primitive like an "int".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic