return / void (Java)
The basic syntax for returning values from methods and for methods with no return value. In Java, you must declare the return type when defining a method. Use a return statement to return a value of the declared type, and use void for methods that return nothing. This page also covers using early return for guard clauses and using arrays, lists, or custom classes to return multiple values.
Syntax
// Basic syntax for a method that returns a value.
// Declare the return type and return a value with the return statement.
returnType methodName(argType argName) {
// logic
return value; // Returns a value that matches the declared type.
}
// Basic syntax for a void method.
// void declares that no value is returned.
void methodName(argType argName) {
// logic
// The return statement can be omitted.
// The method returns automatically when it reaches the end.
}
// A void method can also use return to exit early.
void methodName(argType argName) {
if (condition) {
return; // A return with no value exits the method immediately.
}
// Subsequent logic.
}
Types of return Statements and When to Use Them
| Form | When to use | Description |
|---|---|---|
return value; | Methods with a return value | Returns a value of the declared type to the caller and ends the method. |
return; | void methods | Exits the method immediately without returning a value. If omitted, the method exits automatically at the end. |
| (omitted) | End of a void method | When execution reaches the end of the method, control returns to the caller automatically even without a return statement. |
Sample Code
ReturnBasic.java
public class ReturnBasic {
public static void main(String[] args) {
// --- Basic usage of a method that returns a value ---
// Returns the sorcerer's grade as a string.
System.out.println(getGrade("虎杖悠仁", 80)); // Grade 1
System.out.println(getGrade("五条悟", 100)); // Special Grade
System.out.println(getGrade("乙骨憂太", 95)); // Special Grade
// --- Basic usage of a void method ---
// Only prints sorcerer information; returns no value.
printSorcererInfo("伏黒恵", 70, "Shadow");
printSorcererInfo("七海建人", 72, "Ratio Technique");
}
// A method with a return type of String.
// Returns the grade as a string based on the cursed energy level.
static String getGrade(String name, int cursedEnergyLevel) {
if (cursedEnergyLevel >= 90) {
return name + "'s grade: Special Grade"; // Returns the matched value and exits.
}
if (cursedEnergyLevel >= 70) {
return name + "'s grade: Grade 1";
}
if (cursedEnergyLevel >= 50) {
return name + "'s grade: Grade 2";
}
return name + "'s grade: Grade 3 or below"; // Default return when no condition matches.
}
// A void method.
// Does not return a value; only prints sorcerer info to the console.
static void printSorcererInfo(String name, int cursedEnergyLevel, String technique) {
System.out.println("[" + name + "]");
System.out.println(" Cursed energy level: " + cursedEnergyLevel);
System.out.println(" Technique: " + technique);
// A void method returns automatically at the end without a return statement.
}
}
javac ReturnBasic.java java ReturnBasic 虎杖悠仁's grade: Grade 1 五条悟's grade: Special Grade 乙骨憂太's grade: Special Grade [伏黒恵] Cursed energy level: 70 Technique: Shadow [七海建人] Cursed energy level: 72 Technique: Ratio Technique
ReturnGuardClause.java
public class ReturnGuardClause {
public static void main(String[] args) {
// --- Guard clauses using early return ---
// Reject invalid arguments first to reduce nesting and improve readability.
System.out.println("=== Cursed Power Calculation (with guard clauses) ===");
System.out.println(calcCursedPower("虎杖悠仁", 80, 3));
System.out.println(calcCursedPower(null, 80, 3)); // name is null
System.out.println(calcCursedPower("釘崎野薔薇", -10, 2)); // level is negative
System.out.println(calcCursedPower("伏黒恵", 70, 0)); // multiplier is 0
// --- Early return in a void method ---
System.out.println("\n=== Technique Activation Log ===");
activate("五条悟", 100, true);
activate("乙骨憂太", 95, false); // Sealed, so skipped.
activate("パンダ", 55, true);
}
// A method using guard clauses.
// Uses early return to reject invalid arguments and writes the happy path flat.
static String calcCursedPower(String name, int level, int multiplier) {
// Reject invalid arguments first (guard clauses).
if (name == null || name.isEmpty()) {
return "Error: No name specified."; // Exit early with return.
}
if (level < 0) {
return "Error: Invalid cursed energy level for " + name + ".";
}
if (multiplier <= 0) {
return "Error: Multiplier must be 1 or greater.";
}
// After guard clauses filter out invalid input, write the happy path without nesting.
int result = level * multiplier;
return name + "'s cursed power: " + result;
}
// Guard clause in a void method.
// Uses return; to exit immediately when the condition is not met.
static void activate(String name, int level, boolean isActive) {
if (!isActive) {
System.out.println(name + " is currently sealed and cannot activate the technique.");
return; // In a void method, use return; (no value) to exit.
}
if (level < 60) {
System.out.println(name + " lacks cursed energy to activate.");
return;
}
// Write the happy path flat after the guard clauses.
System.out.println(name + " activated the technique. (Cursed energy level: " + level + ")");
}
}
javac ReturnGuardClause.java java ReturnGuardClause === Cursed Power Calculation (with guard clauses) === 虎杖悠仁's cursed power: 240 Error: No name specified. Error: Invalid cursed energy level for 釘崎野薔薇. Error: Multiplier must be 1 or greater. === Technique Activation Log === 五条悟 activated the technique. (Cursed energy level: 100) 乙骨憂太 is currently sealed and cannot activate the technique. パンダ lacks cursed energy to activate.
ReturnMultipleValues.java
import java.util.ArrayList;
import java.util.List;
public class ReturnMultipleValues {
public static void main(String[] args) {
// --- Returning multiple values via an array ---
// Returns cursed energy stats (min, max, average) as an array.
int[] stats = calcStats(new int[]{80, 100, 70, 95, 72});
System.out.println("=== Cursed Energy Stats (array) ===");
System.out.println("Min: " + stats[0]);
System.out.println("Max: " + stats[1]);
System.out.println("Average: " + stats[2]);
// --- Returning multiple values via a List ---
// Returns names of special grade sorcerers as a List.
List<String> specials = getSpecialGradeSorcerers(
new String[]{"虎杖悠仁", "五条悟", "乙骨憂太", "夏油傑", "伏黒恵"},
new int[]{80, 100, 95, 90, 70}
);
System.out.println("\n=== Special Grade Sorcerers (List) ===");
for (String name : specials) {
System.out.println(name);
}
// --- Returning multiple values via a custom class ---
// Returns detailed sorcerer info bundled in a SorcererResult instance.
SorcererResult result = buildSorcererResult("七海建人", 72, "Ratio Technique");
System.out.println("\n=== Sorcerer Details (custom class) ===");
System.out.println("Name: " + result.name);
System.out.println("Grade: " + result.grade);
System.out.println("Technique: " + result.technique);
System.out.println("Special grade: " + result.isSpecialGrade);
}
// Returns multiple values (min, max, average) bundled in an int array.
static int[] calcStats(int[] levels) {
int min = levels[0];
int max = levels[0];
int sum = 0;
for (int level : levels) {
if (level < min) { min = level; }
if (level > max) { max = level; }
sum += level;
}
return new int[]{min, max, sum / levels.length}; // Returns three values as an array.
}
// Returns only the elements that meet the condition as a List.
static List<String> getSpecialGradeSorcerers(String[] names, int[] levels) {
List<String> result = new ArrayList<>();
for (int i = 0; i < names.length; i++) {
if (levels[i] >= 90) {
result.add(names[i]); // Add to list if cursed energy level is 90 or above.
}
}
return result; // Returns the List.
}
// Returning an instance of a custom class allows bundling multiple values of different types.
static SorcererResult buildSorcererResult(String name, int level, String technique) {
SorcererResult result = new SorcererResult();
result.name = name;
result.grade = level >= 90 ? "Special Grade" : (level >= 70 ? "Grade 1" : "Grade 2 or below");
result.technique = technique;
result.isSpecialGrade = level >= 90;
return result; // Returns the instance.
}
}
// A custom class for bundling multiple values into one.
class SorcererResult {
String name;
String grade;
String technique;
boolean isSpecialGrade;
}
javac ReturnMultipleValues.java java ReturnMultipleValues === Cursed Energy Stats (array) === Min: 70 Max: 100 Average: 83 === Special Grade Sorcerers (List) === 五条悟 乙骨憂太 夏油傑 === Sorcerer Details (custom class) === Name: 七海建人 Grade: Grade 1 Technique: Ratio Technique Special grade: false
Common Mistake 1: Missing return statement on all paths
In a method with a return value, every possible execution path must reach a return statement. Forgetting a return at the end of a conditional branch causes a compile error.
MissingReturnNg.java
public class MissingReturnNg {
// Missing return in the else branch causes a compile error.
static String getGrade(int level) {
if (level >= 90) {
return "Special Grade";
}
// Reaching here returns nothing, causing a compile error.
}
public static void main(String[] args) {
System.out.println(getGrade(75));
}
}
javac MissingReturnNg.java
MissingReturnNg.java:4: error: missing return statement
static String getGrade(int level) {
^
1 error
Either return a value from every branch, or place a default return at the end of the method.
MissingReturnOk.java
public class MissingReturnOk {
static String getGrade(int level) {
if (level >= 90) {
return "Special Grade";
}
if (level >= 70) {
return "Grade 1";
}
return "Grade 2 or below"; // A default return at the end covers all paths.
}
public static void main(String[] args) {
System.out.println(getGrade(75)); // Grade 1
System.out.println(getGrade(60)); // Grade 2 or below
}
}
javac MissingReturnOk.java java MissingReturnOk Grade 1 Grade 2 or below
Common Mistake 2: Returning a value from a void method
A void method declares that it returns no value. Writing return value; causes a compile error. A bare return; with no value can be used for early exit.
VoidReturnNg.java
public class VoidReturnNg {
// This is a void method, but it tries to return a value.
static void printName(String name) {
return name; // Compile error: cannot return a value from method whose result type is void
}
public static void main(String[] args) {
printName("五条悟");
}
}
javac VoidReturnNg.java
VoidReturnNg.java:5: error: cannot return a value from method whose result type is void
return name;
^
1 error
Declare a return type if you want to return a value. Use bare return; if you only want to exit early.
VoidReturnOk.java
public class VoidReturnOk {
// Declare a return type to return a value.
static String getName(String name) {
return name; // Returns a String.
}
// Use bare return in a void method for early exit.
static void printIfNotEmpty(String name) {
if (name == null || name.isEmpty()) {
return; // Bare return for early exit.
}
System.out.println("Sorcerer: " + name);
}
public static void main(String[] args) {
System.out.println(getName("五条悟")); // 五条悟
printIfNotEmpty("乙骨憂太"); // Sorcerer: 乙骨憂太
printIfNotEmpty(""); // Nothing is printed.
}
}
javac VoidReturnOk.java java VoidReturnOk 五条悟 Sorcerer: 乙骨憂太
Common Mistake 3: Unreachable code after return
Code written after a return statement is never executed. The compiler reports a warning (or an error in some environments).
UnreachableNg.java
public class UnreachableNg {
static int calcPower(int base, int multiplier) {
return base * multiplier;
System.out.println("Calculation complete"); // Unreachable after return (compile error).
}
public static void main(String[] args) {
System.out.println(calcPower(300, 3));
}
}
javac UnreachableNg.java
UnreachableNg.java:5: error: unreachable statement
System.out.println("Calculation complete");
^
1 error
Place output or logging before the return statement.
UnreachableOk.java
public class UnreachableOk {
static int calcPower(int base, int multiplier) {
int result = base * multiplier;
System.out.println("Calculation complete: " + result); // Written before return.
return result;
}
public static void main(String[] args) {
System.out.println(calcPower(300, 3));
}
}
javac UnreachableOk.java java UnreachableOk Calculation complete: 900 900
Notes
A return statement ends the method's execution and returns control to the caller. In a method with a return value, a value of the declared type must always be returned, and the code will not compile if any execution path fails to reach a return statement. In a void method, return; (with no value) can be used for early exit; if omitted, the method exits automatically at the end.
A guard clause (early return) is a pattern that uses return to reject invalid arguments or error conditions first. It reduces nesting and allows the happy path to be written flat, improving readability. Writing all conditions as nested blocks without guard clauses leads to deeply nested "arrow code" that is hard to read.
A Java method can return only one value. To return multiple values of the same type, the simplest approach is to bundle them in an array or ArrayList. For values of different types, store them in a custom class instance to return multiple values in a type-safe way. For simple cases, Java 16 and later's record makes this even more concise.
If you find any errors or copyright issues, please contact us.