← Back to Chapters

Java Method Return Types

? Java Method Return Types

? Quick Overview

In Java, a method can return a value to the caller. The return type defines what kind of value a method sends back after execution. Return types make methods reusable, predictable, and type-safe.

? Key Concepts

  • Every Java method must declare a return type
  • void means the method returns nothing
  • Primitive types and objects can be returned
  • The return statement ends method execution

? Syntax / Theory

The return type is written before the method name. The returned value must match the declared type.

? View Code Example
// Method returning an integer value
int add(int a, int b) {
return a + b;
}

? Code Examples

? View Code Example
// Method with void return type
void greet() {
System.out.println("Hello, Java");
}
? View Code Example
// Method returning a String object
String getName() {
return "Debashis";
}

? Live Output / Explanation

Explanation

The add() method returns an integer result, which can be stored in a variable. The greet() method performs an action but returns nothing. The getName() method returns a String object.

? Interactive Simulator

Select a method type to see how data moves!

Variable Storage (Return)
result = 25
Console Output
_

✅ Tips & Best Practices

  • Always match the return value with the declared return type
  • Use void only when no value is needed
  • Avoid unreachable code after return
  • Keep methods focused on a single task

? Try It Yourself

  • Create a method that returns a boolean
  • Write a method that returns the square of a number
  • Convert a void method into one that returns a value