Java Reference
In-Depth Information
• With a while loop, the Java interpreter simply returns to the top of the loop,
tests the loop condition again, and, if it evaluates to true , executes the body of
the loop again.
• With a do loop, the interpreter jumps to the bottom of the loop, where it tests
the loop condition to decide whether to perform another iteration of the loop.
• With a for loop, the interpreter jumps to the top of the loop, where it first eval‐
uates the update expression and then evaluates the test expression to decide
whether to loop again. As you can see from the examples, the behavior of a for
loop with a continue statement is different from the behavior of the “basically
equivalent” while loop presented earlier; update gets evaluated in the for loop
but not in the equivalent while loop.
a x
The return Statement
A return statement tells the Java interpreter to stop executing the current method.
If the method is declared to return a value, the return statement must be followed
by an expression. The value of the expression becomes the return value of the
method. For example, the following method computes and returns the square of a
double square ( double x ) { // A method to compute x squared
return x * x ; // Compute and return a value
Some methods are declared void to indicate that they do not return any value. The
Java interpreter runs methods like this by executing their statements one by one
until it reaches the end of the method. After executing the last statement, the inter‐
preter returns implicitly. Sometimes, however, a void method has to return explic‐
itly before reaching the last statement. In this case, it can use the return statement
by itself, without any expression. For example, the following method prints, but
does not return, the square root of its argument. If the argument is a negative num‐
ber, it returns without printing anything:
// A method to print square root of x
void printSquareRoot ( double x ) {
if ( x < 0 ) return ; // If x is negative, return
System . out . println ( Math . sqrt ( x )); // Print the square root of x
} // Method end: return implicitly
The synchronized Statement
Java has always provided support for multithreaded programming. We cover this in
some detail later on (especially in “Java's Support for Concurrency” on page 208 )—
but the reader should be aware that concurrency is difficult to get right, and has a
number of subtleties.
Search WWH ::

Custom Search