Skip to content

Instantly share code, notes, and snippets.

@artem-smotrakov
Created March 14, 2020 19:26
Show Gist options
  • Save artem-smotrakov/58c9109d837ec1461dfd91b5a4c32d51 to your computer and use it in GitHub Desktop.
Save artem-smotrakov/58c9109d837ec1461dfd91b5a4c32d51 to your computer and use it in GitHub Desktop.
Helpful NullPointerException in Java 14
class A {
public B b;
}
class B {
public C[] array = new C[] { null };
}
class C {
public String string;
}
public class TestNPE {
public static void main(String[] args) {
A a = new A();
try {
a.b.array[0].string = "test";
} catch (Exception e) { // NPE since a.b is null
e.printStackTrace(System.out);
}
a.b = new B();
try {
a.b.array[0].string = "test";
} catch (Exception e) { // NPE since a.b.array[0] is null
e.printStackTrace(System.out);
}
a.b.array[0] = new C();
try {
a.b.array[0].string.length();
} catch (Exception e) { // NPE since a.b.array[0].string is null
e.printStackTrace(System.out);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment