Java Method Return Values
So far our methods just did something, like printing text. Often you want a method to compute a result and hand it back so the rest of your program can use it. That is what a return value is for.
Returning a value
To return a value, replace the void keyword with the type of value the method will send back, such as int, double, or String. Inside the method, use the return keyword followed by the value. As soon as return runs, the method stops and the value is handed to whoever called it.
A method that returns an int
public class Main {
static int addNumbers(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = addNumbers(7, 5);
System.out.println(sum); // 12
// You can use the result directly too
System.out.println(addNumbers(100, 50)); // 150
}
}
// Output:
// 12
// 150The return type in the method header must match the type of the value you actually return. If a method is declared to return int, you cannot return a String, and you must return something on every path out of the method.
Using the returned value
- Store it in a variable: int total = addNumbers(3, 4);
- Print it directly: System.out.println(addNumbers(3, 4));
- Pass it into another method: System.out.println(square(addNumbers(1, 2)));
- Use it in a condition: if (addNumbers(a, b) > 10) { ... }
Returning a boolean for a decision
public class Main {
static boolean isEven(int number) {
return number % 2 == 0;
}
public static void main(String[] args) {
int value = 14;
if (isEven(value)) {
System.out.println(value + " is even");
} else {
System.out.println(value + " is odd");
}
}
}
// Output:
// 14 is evenreturn can also stop a void method
Even a void method can use return by itself, with no value, to exit early. This is handy when you want to skip the rest of the method under certain conditions.
Exiting early with return
public class Main {
static void printGrade(int score) {
if (score < 0) {
System.out.println("Invalid score");
return; // stop here, skip the rest
}
System.out.println("Your score is " + score);
}
public static void main(String[] args) {
printGrade(-5);
printGrade(88);
}
}
// Output:
// Invalid score
// Your score is 88