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