| The method body is where all of the action of a method takes
place; the method body contains all of the legal Java instructions
that implement the method. |
| |
| |
| Returning a Value from a Method |
| We declare a method's return type in its method declaration.
Within the body of the method, we use the return operator to return the value.
Any method that is not declared void must contain a return statement.
The Stack class declares the isEmpty method, which returns a boolean:
|
| |
public boolean isEmpty()
{
if (items.size() == 0)
return true;
else
return false;
} |
| |
| |
| The data type of the return value must match the method's
return type; we can't return an Object type from a method declared to return an integer. |
| The isEmpty method returns either the boolean value true or false, depending
on the outcome of a test. |
| |
| The isEmpty method returns a primitive type. |
| Methods also can return a reference type. |
| |
| For example, |
| Stack declares the pop method that returns the Object reference type: |
| |
public synchronized Object pop()
{
int len = items.size();
Object obj = null;
if (len == 0)
throw new EmptyStackException();
obj = items.elementAt(len - 1);
items.removeElementAt(len - 1);
return obj;
} |