Java Reference
In-Depth Information
ues.length and values[i] .)Afterthesevalueshavebeentotaled,thistotalisre-
turned via the return statement.
Returning from a Method via the Return Statement
Theexecutionofstatementswithinamethodthatdoesnotreturnavalue(itsreturntype
issetto void )flowsfromthefirststatementtothelaststatement.However,Java'sre-
turnstatementletsamethod(oraconstructor)exitbeforereachingthelaststatement.As
Listing2-12 shows,thisformofthereturnstatementconsistsofreservedword return
followed by a semicolon.
Listing 2-12. Using the return statement to return prematurely from a method
class Employee
{
String name;
Employee(String name)
{
setName(name);
}
void setName(String name)
{
if (name == null)
{
System.out.println("name cannot be null");
return;
}
else
this.name = name;
}
public static void main(String[] args)
{
Employee john = new Employee(null);
}
}
Listing2-12 ' s Employee(String name) constructorinvokesthe setName()
instance method to initialize the name instance field. Providing a separate method for
 
Search WWH ::




Custom Search