0

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);
}
het99
  • 13
  • 3

1 Answers1

3

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.

9ilsdx 9rvj 0lo
  • 7,955
  • 10
  • 38
  • 77
  • 3
    In particular, from the [JLS](https://docs.oracle.com/javase/specs/jls/se17/html/jls-16.html) *"For every access of a local variable or blank `final` field `x`, `x` must be definitely assigned before the access, or a compile-time error occurs."* – Federico klez Culloca Oct 14 '21 at 07:17
  • Oh, I got it. Class `varible (variable123)` will be initialized to null by JAVA, while `obj` will not. Thanks @Federico klez Culloca and @9ilsdx 9rvj 0lo. – het99 Oct 14 '21 at 09:46