Blocks |
BASIC |
A block is some number (possibly zero) of declarations and statements, enclosed in braces. A block is itself considered to be a statement.
The body of a method is always a block. However, the braces enclosing the contents of a class or interface are not considered to be a block, and the scope rules and access rules are different. For example:
Control statements, such as if statements and loops, control the execution of a single statement. If you want to control more than just one statement, you can enclose those statements in curly braces to make them into a block (which counts as a single statement). For example:
public class HelloWorld { // not a block String name = "World"; public static void main(String[] args) { // a block System.out.println("Hello, " + name); } }
if (x < y) { int temp = x; x = y; y = temp; }
If x is less than y, the above code interchanges the values of x and y (using a temporary variable); otherwise, it does nothing.
If your block contains declarations (such as int temp = x;
), you
should normally put them first, before the statements in the block. Any variable
you declare inside a block can be used from where you declare it up to the
end of the block--this is the "scope"
of the variable.
A block is the only kind of statement that does not end in a semicolon. Statements within the block, however, do end in semicolons (as usual).
INTERMEDIATE |
Declarations in a block may shadow other declarations.