Java Reference
In-Depth Information
Void Methods
Void methods (methods that do not have a return data type) and value-returning
methods have similar structures. Both have a heading part and a statement part. You can
place user-defined void methods either before or after the method main . However,
program execution always begins with the first statement in the method main .Because
a void method does not return a value of a specific data type using the return
statement, the return type of these methods can be considered void . In a void method,
you can use the return statement without any value; it is typically used to exit the
method early. (Recall that if the compiler can determine that during execution certain
statements in a program can never be reached, then it will generate syntax errors. So be
careful when using a return statement in a void method.) Like value-returning methods,
void methods may or may not have formal parameters.
Because void methods do not return a value of a data type, they are not used (that is,
called) in an expression. A call to a void method is a stand-alone statement. Thus, to call a
void method, you use the method name together with the actual parameters (if any) in a
stand-alone statement. When a void method exits, control goes back to the calling
environment at the statement immediately following the point where it was called.
Before giving examples of void methods, next we give the syntax of void methods.
7
METHOD DEFINITION
The definition of a void method with parameters has the following syntax:
modifier(s) void methodName(formal parameter list)
{
statements
}
The formal parameter list may be empty, in which case, in the method heading, the
empty parentheses are still needed.
FORMAL PARAMETER LIST
A formal parameter list has the following syntax:
dataType variable, dataType variable, ...
METHOD CALL
A method call has the following syntax:
methodName(actual parameter list);
If the formal parameter list is empty, then in the method call statement, empty parenth-
eses are still needed, that is, in this case the method call is: methodName(); .
 
Search WWH ::




Custom Search