Search code examples
javaobjectlocal-variables

java default local object variable initialization


In java OCA book Oracle Certified Associate Java SE 8 Programmer there's this QCM: (Chap 1 question number 12)

A local variable of type Object default to null they respond that's false.

but I think that's a mistake because when we declare this for example : Object obj; as a local variable in a method , the code compiles fine , So the object is null what do you think guys ?


Solution

  • When you declare Object obj; inside a method, obj is uninitialized. This is still totally legal to do, but you cannot access obj without initializing it. If you go a little farther, and write:

    Object local;
    
    if (local == null) {
        // something
    }
    

    The compiler will stop you.