Java AP EXTRA AP LESSON NOTE ONE
LINE STATEMENT BLOCKS We have seen examples with statement
blocks that contain only one line.
Here's an example: if (mark < 50) { System.out.println("You are not passing."); } We can actually write such one-line statement
blocks without the { and } brackets. So, the above could be re-written as: if (mark < 50) System.out.println("You are not passing."); WARNING Not using brackets can be risky. If you decide to add a line to the
statement block, you then have a multi-line block which requires the { and } brackets. Furthermore, it's important to realize
that indenting has no impact on what statements are part of a statement
block. EXAMPLE Let's assume we started with this
program: if (mark < 50) System.out.println("You are not passing."); And then we added another output
statement that should be part of the statement block. if (mark < 50) System.out.println("You are not passing."); System.out.println("You need to work harder."); Now, the second output statement is
not actually part of the statement block.
It is actually after the if-statement and will be executed every
time. The correct version of the above
program would be: if (mark < 50) { System.out.println("You are not passing."); System.out.println("You need to work harder."); } |
|