A method can perform a task and return a result to the code that calls it. You can store that result in a variable or use it in another expression.
In this example, you will create a method that adds two integers and returns their sum.
Source code
public class ReturnValueExample {
void main() {
int firstNumber = 12;
int secondNumber = 8;
int result = add(firstNumber, secondNumber);
IO.println("First number: " + firstNumber);
IO.println("Second number: " + secondNumber);
IO.println("Sum: " + result);
}
int add(int first, int second) {
return first + second;
}
}
Explanation
The add() method accepts two integers and returns an integer:
int add(int first, int second) {
return first + second;
}
Each part of the declaration has a purpose:
| Part | Purpose |
|---|---|
int before add |
Specifies the type of value the method returns |
add |
Names the method |
int first, int second |
Declares the parameters that receive the input values |
return first + second; |
Adds the values and returns the result |
The return statement ends the current method call and sends a value back to the caller.
Inside main(), the following statement calls the method:
int result = add(firstNumber, secondNumber);
The values of firstNumber and secondNumber are passed as arguments. Inside add(), the parameters first and second receive those values.
The method calculates 12 + 8 and returns 20. That value is then assigned to result.
Both main() and add() are instance methods in this example. Java 25 supports an instance main() method, so you can call add() directly without making either method static.
Run the example
Compile and run the file:
javac ReturnValueExample.java
java ReturnValueExample
Output
First number: 12
Second number: 8
Sum: 20
Returning a value versus printing it
The add() method returns its result without printing it. The calling code decides what to do with that value.
For example, you can use the returned value in another calculation:
int doubledSum = add(12, 8) * 2;
Here, add(12, 8) returns 20, which is multiplied by two. The value of doubledSum becomes 40.
Use a return type such as int when a method needs to provide a result. Use void when the method does not return a value.
