Sub topic 3
Return Results or Use void
A method is a named set of instructions that a program can run. Some methods produce a result for the rest of the program to use. Others perform an action without producing a result.
The method’s return type tells Java which kind of result to expect. For a method that does not return a result, the return type is void.
A result travels back to the caller
A method call tells Java to run a method. The code that makes the call is the caller.
A method can use a return statement to send a value back to its caller. A value is a piece of data, such as the number 5 or the text "Pass". When Java runs return, it ends that call to the method.
For example, a call to add(2, 3) can receive the result 5. The caller can save that result or use it in another calculation.
Try a complete program
Save this program in a file named ReturnDemo.java. You need the Java Development Kit installed to run it.
class ReturnDemo {
static int add(int left, int right) {
int total = left + right;
return total;
}
static double half(int number) {
return number / 2.0;
}
static String result(int score) {
if (score >= 60) {
return "Pass";
}
return "Try again";
}
static void showResult(int score) {
if (score < 0 || score > 100) {
System.out.println("Score must be from 0 to 100.");
return;
}
System.out.println(result(score));
}
public static void main(String[] args) {
int total = add(2, 3);
System.out.println(total);
System.out.println(half(7));
String message = result(60);
System.out.println(message);
showResult(50);
showResult(110);
}
}In a terminal, move to the folder that contains the file. Then run:
javac ReturnDemo.java
java ReturnDemojavac is the Java compiler: it checks the source code and prepares it to run. The java command runs the program. You should see:
5
3.5
Pass
Try again
Score must be from 0 to 100.Java starts this program in the main method. The example uses static on its methods so that main can call them directly. You do not need to change the other words in the main line for this example.
Read a return type
Look at the start of the add method:
static int add(int left, int right)
The return type is int, just before the method name, add. An int is a type for whole numbers. The method promises to return an int result.
The names left and right are parameters. A parameter is a named input that a method receives. In the call add(2, 3), the values 2 and 3 are arguments. An argument is a value supplied in a method call.
Inside add, this statement sends the result back:
return total;
The variable total holds the sum. A variable is a named place for a value. Java returns the value of total, not the name itself.
The caller then saves the returned value in its own variable:
int total = add(2, 3);
The two variables happen to have the same name, but they are separate. The one inside add holds the sum while that method runs. The one in main receives the result.
Return different kinds of values
Java uses a type to describe what kind of value a method returns. Here are a few common return types:
| Return type | Kind of result | Example value |
|---|---|---|
| `int` | Whole number | `5` |
| `double` | Number that can have a fractional part | `3.5` |
| `boolean` | Either true or false | `true` |
| `String` | Text | `"Pass"` |
| `void` | No result | None |
The half method returns a double. Its return statement is:
return number / 2.0;
The calculation after return is an expression. An expression is code that produces a value. Java works out the expression first, then returns its value. For half(7), the result is 3.5.
The return type and the returned value must be compatible. For example, a method declared to return int cannot return the text "Pass". Java allows some number conversions: an int value can be returned from a method whose return type is double. But a double value cannot be returned as an int without an explicit conversion.
A double can represent many fractional values, though not every decimal value exactly. That matters when calculations need exact decimal results, such as some money calculations.
Use the returned value
In the example, the caller uses returned values in two ways:
- It saves
add(2, 3)in thetotalvariable. - It passes
half(7)straight toSystem.out.println.
A caller can also use a returned number in a larger expression. For example, add(2, 3) * 2 produces 10.
Java also lets a caller ignore a returned value. A call such as add(2, 3); is allowed on its own. But in this case the result would be lost, because add does not print or save it for the caller.
In the program, add returns 5. The later call to System.out.println(total) is what displays 5.
Return from different paths
The result method chooses a result based on the score:
if (score >= 60) checks whether the score is at least 60. If it is, the method returns "Pass" and ends. Otherwise, Java continues to return "Try again";.
A non-void method must not be able to reach its closing brace without returning a value or ending another way, such as by throwing an exception. An exception is a signal that interrupts normal execution. In this chapter’s examples, each normal path returns a value.
A common mistake is to put the only return inside an if statement. If the condition is false, there may be no result to return. The Java compiler rejects a method if it can reach the end without a required result.
The return type still applies to every returned value. Both "Pass" and "Try again" are text, so both fit the String return type.
Use `void` for no result
The showResult method has return type void:
static void showResult(int score)
This tells Java that the method does not return a value. The method still performs an action: it prints a message.
For a score from 0 to 100, it calls result(score) and prints the returned text. For a score outside that range, it prints an error message instead.
The condition uses ||, which means “or.” It is true if the score is less than 0 or greater than 100.
A void call cannot be used where a value is needed. For example, you cannot save the result of showResult(50) in a variable, because there is no result to save.
Notice that the range check is in showResult, not in result. A direct call to result does not perform that check.
End a `void` method early
A void method can use return; with no value. In showResult, that statement comes after the error message. It ends the current showResult call, so the method does not also print a pass or try-again message.
A void method does not need a return; at the end. When execution reaches its closing brace, the call ends on its own.
Do not put a value after return in a void method. Likewise, a method that returns int or String cannot use a bare return; to supply its result.
Check your understanding
Exercise
What value does half(10) return, and what is its return type?
Show answer
It returns 5.0, with return type double.
Exercise
Why can the program call showResult(50); but not save its result in an int variable?
Show answer
showResult has return type void, so its call produces no value to save.
Exercise
What happens when showResult(110) reaches return;?
Show answer
The current showResult call ends after printing the range message. It does not print a result from result.