Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java variable scope in if statement [duplicate]

I received a compilation error for the following code:

if(true)     int a = 10; else     int b = 20; 

If I change it to the following code, then there is no compilation error:

if(true) {     int a = 10; } else {     int b = 20; } 

Why is the first syntax wrong, and from what language standard?

like image 891
Orup Avatar asked Dec 23 '14 16:12

Orup


People also ask

Can you declare a variable in an if statement in Java?

Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared. This region of the program text where the variable is valid is called its scope .

Can you put a variable in an if statement?

An if-then statement can be used to create a new variable for a selected subset of the observations. For each observation in the data set, SAS evaluates the expression following the if.

Can you have duplicate variable names in a project?

It is legal for 2 variables in different scope to have same name. Please DO read §6.3. Scope of a Declaration from JLS. Below are few of the statement from that section.

Can you define a variable twice in Java?

You can define a constant twice in a block. You can define a variable twice in a block. The value of a variable can be changed. The result of an integer division is the integer part of the division; the fraction part is truncated.


1 Answers

The Java specification says that an if-then-else statement is of the following form:

IfThenElseStatement:     if ( Expression ) StatementNoShortIf else Statement 

Where Statement and StatementNoShortIf can be various things including blocks (code surrounded with braces), assignments (to already declared variables), other if statements etc.

Of note is that declaration statements (e.g. int a; or int a = 10;) are missing from that list, thus you get a compilation error.

For the full list, you can read the Java specification here: http://docs.oracle.com/javase/specs/

like image 162
sunil Avatar answered Oct 14 '22 10:10

sunil