← Back to Chapters

Java return Statement

? Java return Statement

? Quick Overview

The return statement in Java is used to send a value back from a method to the caller and immediately terminate the method execution.

? Key Concepts

  • Ends the execution of a method
  • Can return a value or nothing (void)
  • Must match the method return type
  • Can be used anywhere inside a method

? Syntax / Theory

A method with a return value must use the return keyword followed by a value of the correct type.

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

? Code Examples

? View Code Example
// Complete Java program demonstrating return statement
class ReturnDemo {
static int square(int x) {
return x * x;
}

public static void main(String[] args) {
int result = square(5);
System.out.println(result);
}
}

?️ Live Output / Explanation

Output

25

The method square() returns the square of the number passed to it, which is then printed in the main method.

✅ Tips & Best Practices

  • Always ensure the returned value matches the method return type
  • Use early return to simplify complex logic
  • Avoid unreachable code after a return statement
  • Use meaningful return values for better readability

? Try It Yourself

  • Create a method that returns the maximum of two numbers
  • Write a method that returns true or false based on a condition
  • Convert a void method into one that returns a value