Java Reference
In-Depth Information
The modified printPoem() method knows how to print stanza #1 and #2. If its caller passes a stanza number
outside this range, it prints a message and ends the method call. This is accomplished by using a return statement in
the first if statement. You could have written the above printPoem() method without writing any return statement
as follows:
void printPoem(int stanzaNumber) {
if (stanzaNumber == 1) {
/* Print stanza #1 */
}
else if (stanzaNumber == 2) {
/* Print stanza #2 */
}
else {
System.out.println("Cannot print stanza #" + stanzaNumber);
}
}
The compiler will force you to include a return statement in the body of a method that specifies a return type in
its declaration. However, if the compiler determines that a method has specified a return type, but it always ends its
execution abnormally, for example, by throwing an exception, you do not need to include a return statement in the
method's body. For example, the following method declaration is valid. Do not worry about the throw and throws
keywords at this time; I will cover them in Chapter 9 .
int aMethod() throws Exception {
throw new Exception("Do not call me...");
}
Local Variables
A variable declared inside a method, a constructor, or a block is called a local variable. I will discuss constructors
shortly. A local variable declared in a method exists only for the duration the method is being executed. Because a
local variable exists only for a temporary duration, it cannot be used outside the method, the constructor, or the block
in which it is declared. The formal parameters for a method are treated as local variables. They are initialized with the
actual parameter values when the method is invoked, and before the method's body is executed. You need to observe
the following rules about the usage of local variables.
Rule #1
Local variables are not initialized by default. Note that this rule is the opposite of the rule for instance/class
variable's initialization. When an instance/class variable is declared, it is initialized with a default value. Consider the
following partial definition of an add() method:
int add(int n1, int n2) {
int sum;
/* What is the value of sum? We do not know because it is not initialized yet */
/* More code goes here... */
}
 
Search WWH ::




Custom Search