It's not a secret anymore!
The moose likes Java in General and the fly likes NullPointers in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "NullPointers in Java" Watch "NullPointers in Java" New topic

NullPointers in Java

nandkishor rao
Ranch Hand

Joined: May 24, 2006
Posts: 53
Does a string variable throws NullPointerException if we try to access
if not then why? Is it because it implements toString()?
Krishna Rao

Joined: Nov 15, 2006
Posts: 8
Hi Nandakishore,
String throws Nullpointerexception for sure if it is null.

String s = null;
Gives: Exception in thread "main" java.lang.NullPointerException

Hope this helps
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
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".

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
I agree. Here's the link:
subject: NullPointers in Java
It's not a secret anymore!