Reputation: 1007
If the newWord is null ,it should not go in the loop,but why does it go inside the loop and gives java.lang.NullPointerException
newWord = "abcd";
while(!newWord.equals(null))
{
try {
newWord = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
}
catch(NullPointerException p)
{
}
}
It gives the stacktrace but i have not used printStackTrace() anywhere
Upvotes: 0
Views: 1780
Reputation: 11
to avoid null exception in most of the cases (inside conditional expressions) I advise you to use Yoda conditions:
if(null != value)
Furthemore, this apply to every condition between a variable and a constant:
if(MY_CONSTANT_STRING.equals(myVariableString))
Upvotes: 0
Reputation: 116
The argument for String.equal should not be null and explicitly null is passed so is the exception. Use compound expression to check for empty string and special null.
It tried to evaluate the expression before entering loop, soon the expression is encountered !newWord.equals(null)
, because of newWord
being null an exception were thrown.
Upvotes: 0
Reputation: 3802
the NullPointerException you are getting is because of while(!newWord.equals(null))
and it is not caught because try , catch were used after this code.
If you want to suppress this exception to then put that while(!newWord.equals(null))
in try-catch block.
Upvotes: 0
Reputation: 110
You only check if "newWord" is null, never if "br" has anything left reading from.
Something like:
while(br.hasNext());
Upvotes: 0
Reputation: 533660
It doesn't go into the loop because
newWOrd.equals(null)
will throw an NPE if it is null
What you meant was
newWord != null
You can see this behaviour if you use a debugger, or look at the line in your stack trace where it is triggered.
Upvotes: 1
Reputation: 11006
newWord
itself is null. When an object is null, you can't call any methods on it as the object is not defined. As .equals
is a method, you are getting an exception. Try this instead:
newWord != null
This is a problem easily solved by debugger. Learning to use a debugger is frustrating (as is learning any new tool,) but it will save you many hours of pain. It is your friend.
Upvotes: 8
Reputation: 46428
how about simply
while(newWord!=null)
Think about it, If newWorld is null, what happens when you call methods on it ?
Upvotes: 3