return
- Java course
- Beginner
- Lesson 72/116
- 4 min
Learn to return values with return.
Returning a value
To make a method hand a value back to the caller, use return. The return type then matches the type of the returned value, instead of void.
static int add(int a, int b) {
return a + b;
}
int sum = add(3, 4);
// sum = 7When the method is called, the value of the return expression becomes the result. It can be stored in a variable or printed directly. A method may have more than one return.
Code after return
When return runs inside a method, the flow exits immediately. Code after return never runs; the compiler calls it unreachable code.
static int first(int[] xs) {
return xs[0];
// System.out.println("Never reached");
}If one branch of an if has return, the other branch must also return something. Otherwise you get a compile error.
Practice Compute the square
Define a static int method called square; parameter int n, body return n * n;. Call square(5) from main and print the result.
Starter code
public class Main {
public static void main(String[] args) {
// Call the method with 5 and print the result
}
// Define the square method here
}Sample solution
static int square(int n) {
return n * n;
}
// inside main:
System.out.println(square(5));Expected output
25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match return type to example
| Term | Meaning |
|---|---|
int |
return 7; |
double |
return 3.14; |
String |
return "Merhaba"; |
boolean |
return true; |
2 What happens if println comes after return in static int square(int n)?
static int square(int n) {
return n * n;
System.out.println("never reached");
}- It causes a compile error Correct answer
- println runs before return
- That line never runs
- println runs in an infinite loop
Explanation: Code after return is unreachable; in some cases it is a compile error.
3 Fill in the blank: return the sum
static int add(int a, int b) {
____ a + b;
}
static int add(int a, int b) {
return a + b;
}
Explanation: return a + b; returns the sum.