Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't variables be declared in an if statement?

Tags:

java

scope

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.)

like image 782
Aeronth Avatar asked Jul 03 '13 09:07

Aeronth


6 Answers

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.

like image 62
Darren Avatar answered Oct 23 '22 14:10

Darren


Why? There can be no code path leading to the program assigning 1 to b without declaring it first.

You are right, but the compiler doesn't know that. The compiler does not execute the code. The compiler only translates to bytecode without evaluating expressions.

like image 25
TomWolk Avatar answered Oct 23 '22 12:10

TomWolk


This { } defines a block scope. Anything declared between {} is local to that block. That means that you can't use them outside of the block. However Java disallows hiding a name in the outer block by a name in the inner one. This is what JLS says :

The scope of a local variable declaration in a block (§14.2) is the rest of the block in which the declaration appears, starting with its own initializer (§14.4) and including any further declarators to the right in the local variable declaration statement.

The name of a local variable v may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of v, or a compile-time error occurs.

like image 6
AllTooSir Avatar answered Oct 23 '22 14:10

AllTooSir


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

like image 3
Suresh Atta Avatar answered Oct 23 '22 13:10

Suresh Atta


It is a local variable and is limited to the {} scope.

Try this here.

like image 2
newuser Avatar answered Oct 23 '22 12:10

newuser


you have declared b variable inside if block that is not accessible out side the if block and if you want to access then put outside if block

like image 2
shreyansh jogi Avatar answered Oct 23 '22 12:10

shreyansh jogi