Blocks with a single statement

 

There’s a minor point to be made about statement blocks that has the potential to be a source of trouble if we’re not careful.  If a code block associated with either a conditional statement or a loop has a single statement in it, the curly braces are not required.  For instance in the program above, we could have had

 

            if (num < 0.0)

                  System.out.println(“You entered a negative value.”);

 

With the curly braces omitted, any statement that follows println would not be part of the if block.  The same goes for loops.  Consider the following for loop:

 

            for (int i = 0; i < 10; i++)

                  System.out.println(i);

            System.out.println(“Done.”);

 

The code will print out the values 0 to 9, each on a line, and finally the message “Done.”