Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable default value in Java

Tags:

java

variables

Every type in Java has a primitive value when declared. The article Primitive Data Types contains a description for primitive data types. Knowing this, why does Eclipse show an error telling me the variable may not have been initialized?

If I have, for example,

int x;
x++;
like image 691
Mansuro Avatar asked Mar 13 '12 16:03

Mansuro


2 Answers

From the reference:

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

like image 152
Chikei Avatar answered Oct 10 '22 06:10

Chikei


From the Java Language Specification, Java SE 8 Edition, 4.12.5 Initial Values of Variables:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

like image 31
hmjd Avatar answered Oct 10 '22 06:10

hmjd