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
+3
A:
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.
Jon Skeet
2009-08-14 12:55:10
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
2009-08-14 12:58:14
If `x` is not null, then `if (x.y == null)` will not throw a `NullPointerException`.
Jon Skeet
2009-08-14 12:59:41
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
2009-08-14 13:02:09
Please post your code then.
Jon Skeet
2009-08-14 17:17:20
A:
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);
}
Paul McKenzie
2009-08-14 12:56:29
Then emulate it with "if (....) throw new RuntimeException("assert error ....");
Thorbjørn Ravn Andersen
2009-08-14 13:32:01
+3
A:
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.
ZZ Coder
2009-08-14 13:01:16
A:
I am comparing s==null only
can you show the code snippet that you have written s==null will never throw a NPE
Asif
2009-08-14 13:21:52