Java Reference
In-Depth Information
parentheses are still needed. Thus, a call to a value-returning method with an empty
formal parameter list is:
methodName()
In a method call, the number of actual parameters, together with their data types, must
match the formal parameters in the order given. That is, actual and formal parameters
have a one-to-one correspondence.
As stated previously, a value-returning method is called in an expression. The expression
can be part of an assignment statement, or an output statement, or a parameter in a method
call. A method call in a program causes the body of the called method to execute.
Recall that the heading of the method
main
contains the modifier
static
. The main
objective of this chapter is to learn how to write your own methods and use them in a
Java application program. Therefore, the methods that you will learn to write in this
chapter will be called (used) within the method
main
and/or in other methods of the
class
containing the application program. Because a
static
method cannot call
another nonstatic method of the
class
, the heading of the methods that you will learn to
write in this chapter will contain the modifier
static
. Chapter 8 discusses the
static
methods (members) of a
class
in detail.
7
Next, we describe how a value-returning method returns its value.
return
Statement
A value-returning method uses a
return
(s) statement to return its value; that is, it passes a
value back when the method completes its task.
SYNTAX:
return
STATEMENT
The
return
statement has the following syntax:
return
expr;
where
expr
is a variable, constant value, or expression. The
expr
is evaluated and its
value is returned. The data type of the value that
expr
computes should be compatible
with the return type of the method.
In Java,
return
is a reserved word.
When a
return
statement executes in a method, the method immediately terminates and
the control goes back to the caller.
To put the ideas of this section to work, we'll write a method that determines the larger
of two numbers. Because the method compares two numbers, it follows that this method
has two parameters and that both parameters are numbers. Assume that the data type of
Search WWH ::
Custom Search