1

If implicit constructors automatically initializes all variables to their default values , then why does Java gives compile time errors like " reference variable not initialized" ?

Abhinav
  • 71
  • 1
  • 1
  • 11
  • 1
    Are you sure this error is about field and not some local variable? Can you post some code example with this error? – Pshemo Jul 07 '14 at 20:06
  • Implicit/default constructors do _not_ initialize variables to their default values. To get an answer for why you are getting the "reference variable not initialized" message, you need to provide more context. – Nivas Jul 07 '14 at 20:06
  • possible duplicate of [Uninitialized variables and members in Java](http://stackoverflow.com/questions/268814/uninitialized-variables-and-members-in-java) – Domi Jul 07 '14 at 20:07
  • 3
    That error is for local variables, not fields. The compiler checks local variables more thoroughly as they are easier to reason about as they are limited to one method. – Peter Lawrey Jul 07 '14 at 20:10

2 Answers2

1

Let me clarify variable initialisation:

All the instance variable having primitive data types are initialized to 0, '\0' and false

Whereas all the others are initialized to null.

The local variables are not initialized and will generate a compile time error.

Dhaval Kapil
  • 385
  • 3
  • 10
0

All reference types in a class will be initialized as null if you do not set them to something sensible. I'm not aware of compiler errors for that case.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • I agree, I'm using netbeans 8 and it is capable of detecing a dereferencing of null-pointer (in some cases), but it isn't a compile error. – kajacx Jul 07 '14 at 20:13