The return statement is a very simple one. It just finishes the running of code in the current method and "returns" to the method’s caller.
A method in Java can return a value if the method needs to.
Let’s look at how return statements work with a practical example. Say we have a couple of methods in our program:
int minorHit = 3;
int majorHit = 7;
public boolean adjustHealth(Player player, int hit) {
player.health = player.health - hit;
return isAlive(player);
}
public boolean isAlive(Player player) {
if (player.health >= 20) {
return true;
} else { // player has died!
return false;
}
}If someplace in our code we were to do something like:
// big hit!
boolean isPlayerAlive = adjustHealth(playerOne, majorHit);
if (isPlayerAlive == false) endGame();You can see how when we call the method "adjustHealth()" it returns the result of calling isAlive(player),
and we make a decision to end the game if the player has died.
Notice that you can have multiple return statements in methods. Each return statement can return a different value depending on the conditions.
If a method is marked void then it does not return a value.
However, void methods can still use return statements to stop execution early.
public void printStatus(String message) {
System.err.println(message);
return;
}In this void method, the return statement doesn’t return a value.
It simply signals that the method has finished executing.
Try these exercises in jshell to practice working with return statements and methods:
Exercise 1: Simple Return Method
Create a method that takes two integers and returns their sum:
int addNumbers(int a, int b) {
return a + b;
}Test it: addNumbers(5, 3) should return 8
Exercise 2: Boolean Return Method
Create a method that checks if a number is positive:
boolean isPositive(int number) {
return number > 0;
}Test it: isPositive(5) should return true, isPositive(-3) should return false
Exercise 3: String Return Method
Create a method that returns a greeting message:
String createGreeting(String name) {
return "Hello, " + name + "!";
}Test it: createGreeting("Alice") should return "Hello, Alice!"
Exercise 4: Multiple Return Paths
Create a method that returns different messages based on a grade:
String getGradeMessage(int grade) {
if (grade >= 90) {
return "Excellent!";
} else if (grade >= 70) {
return "Good job!";
} else {
return "Keep trying!";
}
}Test it with different values: getGradeMessage(95), getGradeMessage(75), getGradeMessage(65)