java - When are curly braces not required for multi-line loop bodies? -
why code behave correctly? i've been told multi-line loop bodies should have curly braces
public class sample { public static void main(string[] args) { int[] nums = {1,2,3,4,5,6,7,8,9,10}; // print out whether each number // odd or (int num = 0; num < 10; num++) if (num % 2 == 0) system.out.println(num + " even"); else system.out.println(num + " odd"); } }
the trick here difference between statement , line. loop bodies execute next statement, unless there curly braces, in case loop execute whole block inside curly braces. (as mentioned in other answers, always practice use curly braces every loop , if statement. makes code easier understand, , easier correctly modify.)
to specific example:
an if-else statement in java considered single statement.
in addition, following valid single-line statement:
if(someboolean) someaction(1); else if (someotherboolean) someotheraction(2); else yetanotheraction();
you add many else-if's wanted, , compiler still view single statement. however, if don't use else, views separate line. example:
for(int a=0; a<list.size; a++) if(list.get(a) == 1) someaction(); if(list.get(a) == 2) someotheraction();
this code won't compile, because second if
statement outside scope of for
loop, hence int a
doesn't exist there.
Comments
Post a Comment