namalfernandolk
namalfernandolk

Reputation: 9134

Why local variable MUST be initialized and why instance variables MUST NOT be initialized before using?

I've noticed that the JAVA allows to use uninitialized instance variable but it blocks to use uninitialized local variables. I want to know why the language is saying so?

Note : This is not the first post of this kind. I've visited below questions too. But couldn't find the exact reason for WHY? This question may be a duplicate one of the following:

Upvotes: 2

Views: 1217

Answers (2)

Bui Anh Tuan
Bui Anh Tuan

Reputation: 920

As I know,

  • Instance variable: will be initial at the run time when class initial and default of instance variable is null => instance variable will error at run time.
  • Local variable: Unlike class and instance variables, a local variable is fussy about where you position the declaration for it: You must place the declaration before the first statement that actually uses the variable. => local variable error with syntax error. ref: Local variable in java

Upvotes: 1

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

I've noticed that the JAVA allows to use uninitialized instance variable.

No, the compiler initialize instance variables, if you don't initialize.

Upvotes: 1

Related Questions