Return Values
So far, we've used void methods that perform an action
but don't give anything back. If you want a method to calculate something and
return the result, you use a return value.
The return Keyword
Instead of void, you replace it with the data type of the value you
want to return (e.g., int, String,
double).
Inside the method, use the return keyword to send the value back.
static int calculateSum(int x, int y) {
return x + y; // Returns an integer
}
public static void main(String[] args) {
int result = calculateSum(5, 3);
System.out.println(result); // Outputs 8
}
Rule: If you declare a return type (e.g.,
int),
your method MUST return a value of that type in all possible execution paths.
Using the Return Value
When a method returns a value, you can:
- Store it in a variable:
int x = myMethod(); - Use it directly in an expression:
if (myMethod() > 10) ... - Print it directly:
System.out.println(myMethod());
Output
Click Run to execute your code
Returning Booleans (for Checks)
This is very common for validation methods.
static boolean isEven(int number) {
if (number % 2 == 0) {
return true;
} else {
return false;
}
}
Summary
- Replace
voidwith a data type (e.g.,int) to define a return value. - Use the
returnkeyword to exit the method and pass data back. - A method stops executing immediately when it reaches a
returnstatement.
Enjoying these tutorials?