Return Values

The Course
•
4 min read

A method can give a value back to its caller. Replace void with the returned value’s type, and use a return statement to supply that value. An int-returning method promises that every path that finishes normally returns an int. The caller can store the result, compare it, pass it onward or print it.

Printing and returning are different. A method that only prints a number cannot be used as an int value in another calculation. A method that returns a number does not automatically display it. Choose which responsibility belongs where: calculations usually return results, while main assembles the final report.

Return ends this invocation

After return, that method call is finished. An early return can handle a special case before the normal calculation. It exits the method, not every caller or the entire program. Avoid adding dead statements after an unconditional return; Java can reject code that can never execute.

A contract states the inputs a method accepts and the result it promises. Describe that rule before writing the body. Our remaining method accepts nonnegative planned and completed amounts and returns the uncompleted amount, clamped at zero when completed reaches or exceeds planned. That last phrase is a product rule, not something subtraction does automatically.

Return, then use the result Java
public class Main {
    public static void main(String[] args) {
        int total = twice(15);

        System.out.println(total);
        System.out.println(total + 5);
    }

    static int twice(int minutes) {
        return minutes * 2;
    }
}
Check your prediction
30
35

The returned 30 can participate in another calculation. The helper itself prints nothing. Rename the local variable or replace the first println with a comparison; the helper can remain unchanged.

Guard a finished plan Java
public class Main {
    public static void main(String[] args) {
        System.out.println(remaining(40, 15));
        System.out.println(remaining(40, 40));
        System.out.println(remaining(40, 50));
    }

    static int remaining(int planned, int completed) {
        if (completed >= planned) {
            return 0;
        }

        return planned - completed;
    }
}
Check your prediction
25
0
0

The first call reaches subtraction. The other two finish at the early return. These are three distinct boundary cases: less than, equal to and greater than the planned amount.

Compiler error: not every path returns Java
public class Main {
    public static void main(String[] args) {
        System.out.println(discount(5));
    }

    static int discount(int count) {
        if (count >= 10) {
            return 2;
        }
    }
}
Read the diagnostic

When count is below 10, execution reaches the method end with no int result. Add a result for that path. A successful branch does not fulfill the contract for every input.

Your turn

Exercise

Calculate remaining minutes

Implement remaining(planned, completed) using the contract above. Edit the body of remaining; keep its name, parameter types and return type unchanged. Press Run to see a result for each case. This practice editor calls the method directly instead of running main: (40,15) gives 25, (40,40) gives 0, (40,50) gives 0 and (0,0) gives 0. Values are nonnegative. The result must be returned, not just printed.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println(remaining(40, 15));
    }

    static int remaining(int planned, int completed) {
        // Replace this placeholder with your rule.
        return 0;
    }
}
Hint 1: the idea

Handle completion reaching the plan as one branch; otherwise compute the difference.

Hint 2: a first step

The early-return branch includes equality. Put the subtraction after that branch, so it is reached only for unfinished work.

Show one solution
public class Main {
    public static void main(String[] args) {
        System.out.println(remaining(40, 15));
    }

    static int remaining(int planned, int completed) {
        if (completed >= planned) {
            return 0;
        }

        return planned - completed;
    }
}
25

Change it and explain

The practice editor deliberately calls remaining directly; it does not run main. Its case list compares returned values with expectations. The solution’s output block shows what its ordinary main would print. All cases are visible so you can understand the contract; passing them is not proof for every future input.

Add a new case mentally before changing the code: planned=1, completed=0. Then call the method from two different reports. Explain why returning a value makes this reuse easier than embedding all wording inside the calculation method.

Was this article helpful?

Your response is saved on this device.