Consider the following method:
void a () { int x; boolean b = false; if (Math.random() < 0.5) { x = 0; b = true; } if (b) x++; }
In x++I get the error "The local variable may not have been initialized." Clearly, x will never be used without initialization. Is there any way to suppress a warning except initializing x? Thank.
x++
No, there is no way Javato check all possible code paths for a program to determine if a variable has been initialized or not, so it takes a safe route and warns you.
Java
No, you have to initialize your variable to get rid of this.
:
void a () { if (Math.random() < 0.5) { int x = 1; } }
. .
, , . , .
void a () { int x; boolean b = false; if (Math.random() < 0.5) { x = 0; b = true; x++; } if (b) { //do something else which does not use x } }
, x if, x if, , , x.
x
EDIT: :
void a () { int x; boolean b = (Math.random() < 0.5); if (b) { x=1 //do something } }