if(condition) The braces used are actually only necessary if there is more than one statement to be perfromed if the condition is true. If there are no braces, only one statement is considered to be tied to the if. Let's look at some examples. if(x < 10) is equivalent to if(x < 10) or even if(x < 10) System.out.println("Single-digit number");
if(x < 10) if(x < 10) In the first if, both SOPln statements will only perform if x<10. In the second, only the first SOPln statement is tied to the if. The second one will perform no matter what the result of the condtion is. Indentation does not determine whether a statement is connected to an if, braces do. In closing, while it is not necessary to put braces for one statement, programmers tend to do so as a good practice. One advantage is not having to remember them later when another statement is added to the if block.
|
|||||||||||
© DanShuster.com