Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error on if condition java

Tags:

java

public class SomeClass{

    public static void main (String[] args){
        if(true) int a = 0;// this is being considered as an error 
        if(true){
            int b =0;
        }//this works pretty fine
    }
}//end class

In the above class first if statement is showing an compilation error

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    Syntax error on token "int", delete this token
    a cannot be resolved to a variable

However second if statement works fine. I just cannot figure it out myself. I know it is of no use declaring a variable in a single statement if. How those two statements are different can some one please explain me. Excuse me if the question is really simple.

like image 510
wh0 Avatar asked Nov 27 '22 21:11

wh0


2 Answers

To define the scope of int a you need curly braces. That's why you get compiler error for

if(true) int a = 0;

while this works :

if(true){
    int b =0;
}

See JLS §14.9 for if statements,

IfThenStatement:
    if ( Expression ) Statement

While in if(true) int a = 0;, int a = 0 is LocalVariableDeclarationStatement

like image 190
Nandkumar Tekale Avatar answered Dec 15 '22 02:12

Nandkumar Tekale


It is specified in the java language specification. The IfThenStatement is specified as

if ( Expression ) Statement

int a = 0; is not a statement, but a LocalVariableDeclarationStatement (which is not a subtype of Statement). But a Block is a Statement and a LocalVariableDeclarationStatement is legal content of a block.

 if (true) int a = 0;
           ^--------^    LocalVariableDeclarationStatement, not allowed here!

 if (true) {int a = 0;}
           ^----------^  Statement (Block), allowed.

Reference

  • Local Variable Declaration Statements
  • Statements
  • The If Statement
like image 30
Andreas Dolk Avatar answered Dec 15 '22 03:12

Andreas Dolk