There is a possiblity that this may be a dupicate question. I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this variable is not equal to null and whatever I try I get a null pointer exception.I can't afford to throw nullpointer exception as it is costly.Is there any workaround that is efficient.TIA
-
Maybe look at http://stackoverflow.com/questions/271526/how-to-avoid-null-statements-in-java – Artelius Aug 14 '09 at 12:53
-
2Show us the code. Your explanation does not conform with my experiences. Also enable null-checks in the compiler if possible (e.g. with Eclipse) – Thorbjørn Ravn Andersen Aug 14 '09 at 13:33
-
Forgot to restart the server and that was the problem.Problem solved – Aug 17 '09 at 02:43
5 Answers
If you use
if (x == null)
you will not get a NullPointerException
.
I suspect you're doing:
if (x.y == null)
which is throwing because x
is null, not because x.y
is null.
If that doesn't explain it, please post the code you're using to test for nullity.

- 1,421,763
- 867
- 9,128
- 9,194
-
Ya you got it right.I have the variable y declared as null in X class.However X is not null.No exception is thrown for non null values – Aug 14 '09 at 12:58
-
1If `x` is not null, then `if (x.y == null)` will not throw a `NullPointerException`. – Jon Skeet Aug 14 '09 at 12:59
-
X cannot be null because I am passing X.z to another function as parameter just before this line which is not throwing null pointer exception – Aug 14 '09 at 13:02
I guess you are doing something like this,
String s = null;
if (s.equals(null))
You either check for null like this
if (s == null)
A better approach is to ignore the null and just check for the expected value like this,
if ("Expected value".equals(s))
In this case, the result is always false when s is null.

- 74,484
- 29
- 137
- 169
String is immutable
@Test(expected = NullPointerException.class)
public void testStringEqualsNull() {
String s = null;
s.equals(null);
}
@Test
public void testStringEqualsNull2() {
String s = null;
TestCase.assertTrue(s == null);
}

- 19,646
- 25
- 76
- 120
I am comparing s==null only
can you show the code snippet that you have written s==null will never throw a NPE

- 11
- 2
-
You are right...The reason for the exception was I was originally comparing s!=null||s.equals("") and the or part was throwing nullpointerException.However I removed that but forgot to restart the server.Thanks for ur responses – Aug 17 '09 at 02:42
if you are checking whether "s" is null, then do not apply a dot(.) after "s". Doing that would throw NullPOinterException, as applying dot(.) means that you are trying to access on a pointer location which is basically null at the moment !
Also try to use library functions that check whether a string is null or empty. you may use StringUtils.isEmpty(s) from apache library which checked both

- 11
- 1