John Snow
John Snow

Reputation: 1007

Loop Null Pointer Exception

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

Answers (8)

user3785783
user3785783

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

Twinkle
Twinkle

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

rocketboy
rocketboy

Reputation: 9741

!newWord.equals(null)

is your problem.

Use newWord != null

Upvotes: 0

Sachin Verma
Sachin Verma

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

ThisAndThat
ThisAndThat

Reputation: 110

You only check if "newWord" is null, never if "br" has anything left reading from.

Something like:

while(br.hasNext());

Upvotes: 0

Peter Lawrey
Peter Lawrey

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

William Morrison
William Morrison

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

PermGenError
PermGenError

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

Related Questions