Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd compiler error on if-clause without braces

The following Java code is throwing a compiler error:

if ( checkGameTitle(currGame) )
    ArrayList<String> items = parseColumns( tRows.get(rowOffset+1), currGame, time, method );

checkGameTitle is a public static function, returning a boolean. The errors are all of the type "cannot find symbol" with the symbols being variable ArrayList, variable String and variable items.

However, if I add {curly braces} then the code compiles with no errors. Why might this be? Is there some ambiguity on the if clause without them?

like image 362
DisgruntledGoat Avatar asked Mar 27 '10 03:03

DisgruntledGoat


People also ask

Can we use if statement without curly braces?

Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces. But it is Highly Recommended to use curly braces. Because if the user (or someone else) ever expands the statement it will be required.

Do you need brackets for if statements?

If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.

Does IF statement need curly braces Java?

Java has a "feature" which allows you to omit curly brackets when writing if statements, for loops, or while loops containing only a single statement. You should never use this feature – always include curly brackets. The reason for this is because omitting curly brackets increases your chances of writing buggy code.

When can curly braces be omitted from an if statement?

If there is only one statement for the if condition, curly braces are optional but if there are a series of steps curly braces are mandatory. That being said, you always want to keep the option of adding more statements to an if condition later. It is more readable and reduces error or bugs.


1 Answers

If you declare a variable items at this point, it's not accessible from anywhere. So it would make no sense to allow this construct.

OTOH, when you open a block, it still makes no sense to do the same thing (at first). But it's expected, that you'll want to extend the block later, and that it will eventually make sense.

like image 162
Chris Lercher Avatar answered Oct 23 '22 15:10

Chris Lercher