Skip to content

Return Types

This content is for Java. Switch to the latest version for up-to-date documentation.

Every method in Java must declare a return type, which specifies what kind of value the method will return to the caller.

When a method doesn’t return any value, use void:

public void printMessage(String message) {
System.out.println(message);
// No return statement needed
}

Methods can return any primitive data type:

public int add(int a, int b) {
return a + b;
}
public double calculateArea(double radius) {
return Math.PI * radius * radius;
}
public boolean isAdult(int age) {
return age >= 18;
}
public char getFirstCharacter(String text) {
if (text != null && text.length() > 0) {
return text.charAt(0);
}
return '\0'; // null character
}

Methods can return objects (reference types):

public String formatName(String firstName, String lastName) {
return lastName + ", " + firstName;
}
public Date getCurrentDate() {
return new Date();
}
public int[] getEvenNumbers(int count) {
int[] result = new int[count];
for (int i = 0; i < count; i++) {
result[i] = i * 2;
}
return result;
}
  • The return statement exits the method immediately
  • For non-void methods, a return statement with a value is required
  • Multiple return statements are allowed
public String getLetterGrade(int score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
if (score >= 60) return "D";
return "F";
}

The returned value must be compatible with the declared return type:

public int getNumber() {
return 42; // OK
// return 3.14; // Error: double cannot be converted to int
// return "42"; // Error: String cannot be converted to int
}
public Object getObject() {
return "Hello"; // OK: String is a subclass of Object
// return 42; // OK: autoboxed to Integer which is a subclass of Object
}

When overriding methods, the return type can be a subclass of the original return type:

class Animal { }
class Dog extends Animal { }
class AnimalShelter {
public Animal getAnimal() {
return new Animal();
}
}
class DogShelter extends AnimalShelter {
@Override
public Dog getAnimal() { // Covariant return type
return new Dog();
}
}
public Optional<User> findUserById(int id) {
User user = database.lookup(id);
return Optional.ofNullable(user);
}
public class StringBuilder {
public StringBuilder append(String str) {
// append the string
return this; // Return this object for chaining
}
}
// Usage
new StringBuilder()
.append("Hello")
.append(" ")
.append("World");
public class Result {
private final boolean success;
private final String message;
private final Object data;
// constructor and getters
}
public Result saveUser(User user) {
try {
database.save(user);
return new Result(true, "User saved successfully", user);
} catch (Exception e) {
return new Result(false, e.getMessage(), null);
}
}
Built with passion by Ngineer Lab