The following Java code does not compile.
int a = 0;
if(a == 1) {
int b = 0;
}
if(a == 1) {
b = 1;
}
Why? There can be no code path leading to the program assigning 1 to b
without declaring it first.
It occurred to me that b
's variable scope might be limited to the first if
statement, but then I wouldn't understand why. What if I really don't want to declare b
needlessly, in order to improve performance? I don't like having variables left unused after declaration.
(You may want to argue than I could simply declare b in the second if
statement, in that case, just imagine that it could be in a loop somewhere else.)
Because when b goes out of scope in the first if (a == 1) then it will be removed and no longer exists on the stack and therefore can not be used in the next if statement.
Variables can be declared inside a conditional statement. However you try and access
b
in a different scope.When you declare b here:
It is only in scope until the end
}
.Therefore when you come to this line:
b
does not exist.The scope of b is the block it is declared in, that is, the first if. Why is that so? Because this scoping rule (lexical scoping) is easy to understand, easy to implement, and follows the principle of least surprise.
If b were to be visible in the second if:
No sane language has such a complicated scoping rule.
w.r.t. performance - declaring an extra variable has a negligible impact on performance. Trust the compiler! It will allocate registers efficiently.
If you re declaring variable inside a block then the limitation of the variable limits to the particular block in which it got declared.
NOTE : Only static variables has access from anywhere in the program.
In you code :
variable 'a' can be accessed in any if statement as its declare outside the block but, variable 'b' is declare inside if hence limited its use outside the block.
If you want to use 'b' outside the if statement you have to declare it where you have declare variable 'a'.
you have to do following way to make correct the error
Its all about java variable scoping.
You'll need to define the
variable
outside of the ifstatement
to be able to use it outside.See Blocks and Statements