Java Reference
In-Depth Information
then the method always returns a value of type
double
, and the heading
public
String yourMethod()
indicates a method that always returns a value of type
String
.
The following is a
void
method heading:
public void
ourMethod()
Notice that when the method returns no value at all, we use the keyword
void
in place
of a type. If you think of
void
as meaning “no returned type,” the word
void
begins to
make sense.
An
invocation
of a method that returns a value can be used as an expression any-
place that a value of the
Type_Returned
can be used. For example, suppose
anObject
is
an object of a class with methods having our sample heading; in that case, the follow-
ing are legal:
invocation
double
d = anObject.myMethod();
String aStringVariable = anObject.yourMethod();
A
void
method does not return a value, but simply performs an action, so an invo-
cation of a
void
method is a statement. A
void
method is invoked as in the following
example:
anObject.ourMethod();
Note the ending semicolon.
So far, we have avoided the topic of parameter lists by only giving examples with
empty parameter lists, but note that parentheses are required even for an empty
parameter list. Parameter lists are discussed later in this chapter.
The
body
of a
void
method definition is simply a list of declarations and state-
ments enclosed in a pair of braces,
{}
. For example, the following is a complete
void
method definition:
body
public void
ourMethod()
{
System.out.println("Hello");
System.out.println("from our method.");
}
The body of a method that returns a value is the same as the body of a
void
method
but with one additional requirement. The body of a method that returns a value must
contain at least one
return
statement. A
return
statement
is of the form
return
statement
return
Expression
;