Statements and expressions in Java appear within a code block. A code block is syntactically a series of statements surrounded by an open curly brace ({) and a close curly brace (}). The statements in a code block can include variable declarations and most of the other sorts of statements and expressions we mentioned earlier:
{
int size = 5;
setName("Max");
...
}
Methods, which look like C functions, are in a sense just code blocks that take parameters
and can be called by their names—for example, the method setUpDog():
setUpDog( String name ) {
int size = 5;
setName( name );
...
}
Variable declarations are limited in scope to their enclosing code block—that is, they
can’t be seen outside of the nearest set of braces:
{
int i = 5;
}
i = 6; // Compile-time error, no such variable i
In this way, code blocks can be used to arbitrarily group other statements and variables.
The most common use of code blocks, however, is to define a group of statements for
use in a conditional or iterative statement.
0 comments:
Post a Comment