views:

159

answers:

5

Hi every one,

I do a condition with a value when it is null and when it is not null. The time where this value is null i got the java.lang.NullPointerException.

How could i deal with this in order to dismiss this exception. I need the condition when the value is null and when it is not.

Thanks for help.

+3  A: 

Simply do a proper check for the value being null. A conditional such as

if (value == null)

will never raise a NullRefePointerException. It's only if you try accessing whatever a null reference points to that you get the exception. So calling methods or accessing other instance members of the object is out of question.

Joey
A: 

Really confuse question but :

boolean isNull=true; if (value != null) {isNull=false;}

Olivier
+1  A: 

Use an IF to check for the variable not being null and then use ELSE code block for when it is null.

if (variable != null)
{
    //code when object is not null
}
else
{
    //code when object is null
}

The null pointer is only throwh when you try and use the null value

e.g

 variable.method();

But you should always avoid a situation where a null pointer could occur

Chris
+1 although I'm not happy with the last sentence. Sometime we get `null` from API calls or want to store `NULL` results from database queries. So it's not always avoidable.
Andreas_D
+4  A: 

You get a NullPointerException when you try to call a method using a variable that is null. Simple example:

String s = null;
int len = s.length();  // NullPointerException because s is null

So you should check if the variable is null before calling any method on it, for example:

int len;
if (s == null) {
    len = 0;
}
else {
    len = s.length();  // safe, s is never null when you get here
}

Note that a NullPointerException is usually easy to solve. Carefully look at the stack trace of the exception, it tells you exactly in which line of your code the exception happens. Check what could be null in that line of code, and check if you're calling a method on something that might be null. Add a check (or prevent that the relevant thing can ever be null in another way).

Jesper
+1  A: 

As stated by other posters, if you do not expect the s reference to be null here then fix the bug that causes the reference to be null in the first palce. However, if it is valid that the reference could be null, you can also do the following using the ternary operator (Java 5 on)

int len = (s == null) ? 0 : s.length;

note: the brackets are optional but make it a bit more readable in my opinion.

dairemac