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?
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 .
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With