Operators · Lesson 6/8
75%
⏱ 10–15 min

Java return Statement

The return statement in Java is used to explicitly exit a method and optionally return a value to the caller.

If a method is declared with a void return type, the return statement is not required. However, it can be used to exit the method early, as shown in the following example:

public class ReturnExample1 {
    public static void main(String[] args) {
        boolean t = true;
        System.out.println("Before return.");
        if (t) {
            return;
        }
        System.out.println("This line will not be executed.");
    }
}

Output of this code:

Before return.

Using return to Return a Value

If a method is declared to return a value, the return statement must be used. It must be followed by the value that should be returned from the method:

public class ReturnExample2 {
    public static void main(String[] args) {
        double d = getRandomValue(3);
        System.out.println(d);
    }

    public static double getRandomValue(int i) {
        return Math.random() * i;
    }
}

Java Core

1. Java Introduction
2. Run Your First Java App
3. Java Syntax
4. Java Operations
5. Operators
6. Arrays
7. Sorting Algorithms
8. OOP Basics
9. Lambda Expressions
10. Stream API
11. Inner Classes and Exceptions
12. Git & GitHub
‹ Previous lesson Next lesson ›