i want to understand from the below code y the value of static variable b was not initialized and though the value was initialized in the constructor.
public class A {
private static B b = null;
public A() {
if (b == null)
b = new B();
}
public static void main(String[] args) {
b.func();
}
}
Thanks
Punith
You never call the A() constructor.
main function is static, that means that it doesnt “belong” to an instance of A.
So when you enter main, no instance of A has been created so A constructor has never been called and b is still null.
You should get a NullPointerException if you run this code.
If you add
new A();
before the b.func(); then you will be okay (code will still be odd)