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

前端 未结 13 1835
感动是毒
感动是毒 2020-12-05 10:18

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

13条回答
  •  被撕碎了的回忆
    2020-12-05 11:01

    { } 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

提交回复
热议问题