Home > Back-end >  Object reference is not initialized as null in JAVA
Object reference is not initialized as null in JAVA

Time:10-14

According to rule in JAVA if object reference is declared but not initialized then JAVA initializes it by null. So why is this error is occuring in my code ? Plaese help me out.

Main.java:28: error: variable obj might not have been initialized
        if(obj==null)
           ^
class c {
    int age=12;
    c variable123;
}
public class A {
    c obj;
    if (obj==null) System.out.println(obj);
}

CodePudding user response:

You've misread the documentation. The class (non-final) variables are initialized with null values, the local values are not initialized and cause compiler error.

See https://docs.oracle.com/javase/specs/jls/se17/html/jls-16.html for details.

  • Related