Null pointer exception

There is a possibility that this could be a duplicate question. I initialize the String variable to null. I can or cannot update it with a value. Now I want to check if this variable is not equal to zero and what I'm trying to get. The exception is the null exception. I cannot afford to throw an nullpointer exception, as it is expensive. Is there any workaround that is .TIA effective

+3
source share
4 answers

If you use

if (x == null)

you will not receive NullPointerException.

I suspect you are doing:

if (x.y == null)

, x null, , x.y null.

, , , .

+3

, - ,

  String s = null;

  if (s.equals(null))

null

  if (s == null)

, ,

  if ("Expected value".equals(s))

false, s null.

+3

@Test(expected = NullPointerException.class)
public void testStringEqualsNull() {
    String s = null;
    s.equals(null);
}

@Test
public void testStringEqualsNull2() {
    String s = null;
    TestCase.assertTrue(s == null);
}
+1
source

I compare only s == null

you can show the code snippet you wrote s == null will never throw NPE

+1
source

Source: https://habr.com/ru/post/1715169/


All Articles