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 pa
Just for completeness sake: this one works as well (explanation is scoping, see the other answers)
int a = 0;
if(a == 1) {
int b = 0;
}
if(a == 1) {
int b = 1;
}
Due to scoping, b will only be accessible inside the if statements. What we have here are actually two variables, each of which is just accessible in their scope.
Its all about java variable scoping.
You'll need to define the variable
outside of the if statement
to be able to use it outside.
int a = 0;
int b = 0;
if(a == 1) {
b = 1;
}
if(a == 1) {
b = 2;
}
See Blocks and Statements
int a = 0;
if(a == 1) {
int b = 0; // this int b is only visible within this if statement only(Scope)
}
if(a == 1) {
b = 1; // here b can't be identify
}
you have to do following way to make correct the error
int a = 0;
int b = 0;
if(a == 1) {
b=0;
}
if(a == 1) {
b = 1;
}
Variables can be declared inside a conditional statement. However you try and access b
in a different scope.
When you declare b here:
if(a == 1) {
int b = 0;
}
It is only in scope until the end }
.
Therefore when you come to this line:
b = 1;
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.
variable b's scope is only until the if block completes, as this is where you declared the variable. That is why it cannot be accessed on the following block. This is for memory allocation, otherwise they would be ALOT of variables floating around in the memory.
int a = 0;
if(a == 1) {
int b = 0;
} //b scope ends here
if(a == 1) {
b = 1; //compiler error
}