Java Return
Return Values
In the previous page, we used the void
keyword in all examples, which indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as int
,
char
, etc.) instead of void
, and use the return
keyword inside the method:
Example
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)
This example returns the sum of a method's two parameters:
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
System.out.println(myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read and maintain):
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int z = myMethod(5, 3);
System.out.println(z);
}
}
// Outputs 8 (5 + 3)
Practical Example
Here is a simple and fun "game example" using a method that returns a value,
to show the double of the numbers 1 through 5 (using a for
loop):
Example
public class Main {
// Method that doubles the number
static int doubleGame(int x) {
return x * 2;
}
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Double of " + i + " is " + doubleGame(i));
}
}
}