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

前端 未结 13 1811
感动是毒
感动是毒 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:10

    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 :

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

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

    0 讨论(0)
提交回复
热议问题