I was trying to execute the following code:
public class StaticTest {
private static List<String> dat1;
{
dat1 = new ArrayList<>();
}
private StaticTest(){
System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
}
public static void main(String[] args) {
System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
new StaticTest();
}
}
I tried to execute the above code, I got Null pointer exception at Marked Line 1. But when I commented Marked Line 1 I got the output.
Why am I getting the exception in first case and not in second ?
When I use private static List<String> dat1= new ArrayList<>();, no exception is thrown.