Why can't variables be declared in an if state

2019-01-23 14:21发布

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

标签: java scope
13条回答
叛逆
2楼-- · 2019-01-23 14:47

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

Try this here.

查看更多
该账号已被封号
3楼-- · 2019-01-23 14:48

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

查看更多
够拽才男人
4楼-- · 2019-01-23 14:50

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
}
查看更多
唯我独甜
5楼-- · 2019-01-23 14:54

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.

查看更多
太酷不给撩
6楼-- · 2019-01-23 14:57

{ } is used to define scope of variables.And here you declared :

if(a == 1) 
{
    int b = 0;
}

So here scope of b will be only in { }.So you are using variable b outside { }, it is giving compilation error.

You can also refer this:

http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html

查看更多
做自己的国王
7楼-- · 2019-01-23 15:01

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.

查看更多
登录 后发表回答