-3

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 ?

Naman
  • 27,789
  • 26
  • 218
  • 353
Anas Hadhri
  • 159
  • 1
  • 2
  • 9

1 Answers1

3

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.

Ben P.
  • 52,661
  • 6
  • 95
  • 123
  • 1
    The spec lays it out pretty nicely, and also points out the difference to e.g. class variables: https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5 – TimoStaudinger Jan 16 '20 at 21:09