Java Reference
In-Depth Information
where
Expression
can be any expression that evaluates to something of the
Type_Returned
that is listed in the method heading. For example, the following is a complete definition
of a method that returns a value:
public
String yourMethod()
{
Scanner keyboard =
new
Scanner(System.in);
System.out.println("Enter a line of text");
String result = keyboard.nextLine();
return
result + " was entered.";
}
Notice that a method that returns a value can do other things besides returning
a value, but style rules dictate that whatever else it does should be related to the
value returned.
A
return
statement always ends a method invocation. Once the
return
statement
is executed, the method ends, and any remaining statements in the method definition
are not executed.
If you want to end a
void
method before it runs out of statements, you can use a
return
statement without any expression, as follows:
return
in a
void
method
return
;
A
void
method need not have any
return
statements, but you can place a
return
statement in a
void
method if there are situations that require the method to end
before all the code is executed.
Method Definitions
There are two kinds of methods: methods that return a value and methods, known as
void
methods, that perform some action other than returning a value.
Definition of a Method That Returns a Value
SYNTAX
public
Type_Returned Method_Name(Parameter_List)
{
<List of statements, at least one of which
must contain a return statement.>
}
If there are no
Parameters
,
then the parentheses are empty.