Java Reference
In-Depth Information
2.3.2 Nested blocks and variable scopes
Blocks can be nested. This naturally occurs in the case of if-else structures
that may internally contain other conditional structures. But this may also be
possible without conditional structures for controlling the scope of variables.
Indeed, variables defined in a block are defined for all its sub-blocks. Thus
a variable cannot be redefined in a sub-block. Moreover variables defined in
sub-blocks cannot be accessed by parent blocks as illustrated by the following
example:
class NestedBlock
{ public static void main( String [ ]
arg )
int i=3;
int j=4;
System . out . println ( "i=" +i+ "j=" +j ) ;
// Cannot redefine a variable i here
int ii=5;
j ++;
i −− ;
}
System . out . println ( "i=" +i+ "j=" +j ) ;
// Cannot access variable ii here
}
}
i=3 j=4
i=2 j=5
Finally note that single instructions in control structures such as if-else are
interpreted as implicit blocks where braces are omitted for code readibility.
2.4 Looping structures
Loop statements are fundamental structures for iterating a given sequence of
instructions, repeating a block of instructions. Java provides three kinds of
constructions for ease of programming, namely: while , for and do-while .
Theoretically speaking, these three different constructions can all be emulated
with a while statement. We describe the semantic of each structure by
illustrating it with concrete examples.
 
Search WWH ::




Custom Search