Skip to content

Return Values

The Course
•
20 min study

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
Text
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
Text
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.

Separate a result from its presentation

Returning and printing solve different problems. return gives a value back to a caller, which can store it, compare it or use it in another calculation. println sends text to the output panel. A helper that only prints a number cannot supply that number to another expression.

Trace remaining(30, 10): the method returns 20, then main decides whether to display "20 min left" or use 20 to plan another block. There is one calculation and two possible uses. If completed already meets the plan, the early return gives zero and the later subtraction is not executed.

Check the contract before deciding whether negative inputs are allowed. Today's exercise assumes nonnegative plan and completion values. That assumption keeps this method focused; Day 6 will teach you to reject invalid data at a boundary rather than adding arbitrary fallback answers.

Debug a plausible mistake

This task combines a Day 2 decision with a returned value. The print statements are correct callers; the helper's implementation fails one part of its contract. Fix the decision inside the reusable helper rather than special-casing one message in main.

Exercise

Repair the returned result

remaining must return zero when completed meets or exceeds planned. For the calls below print 20 then 0. Keep the actual subtraction for unfinished plans. Predict what the current program actually prints before changing it. Make the smallest repair, then add the exact-equality call remaining(30, 30), which should print 0. The supplied version compiles; its behavior is the problem.

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

    static int remaining(int planned, int completed) {
        return planned - completed;
    }
}
Hint 1: the idea

A valid arithmetic result can still violate the method's nonnegative-result promise.

Hint 2: a first step

Handle the completed case before returning the ordinary subtraction.

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

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

Expected output after repair:

Text
20
0

The bug was a missing branch: plain subtraction returned −10 for (30, 40). The early return 0 runs first whenever completed has reached the plan, so the subtraction below it only ever sees unfinished work.

Your turn

Exercise

Count study blocks

Study time is booked in blocks of 25 minutes, and a partly used block still counts as a whole block. Write blocksNeeded(minutes), which returns how many blocks a plan of that many minutes needs. Contract: minutes is 0 or more.

minutesblocks
00
101
251
262
502

Edit only the body of blocksNeeded; keep its name, parameter and return type. Press Run to see a result for each case: this practice editor calls the method directly instead of running main. The result must be returned, not just printed.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println(blocksNeeded(26));
    }

    static int blocksNeeded(int minutes) {
        // Replace this placeholder with your rule.
        return 0;
    }
}
Hint 1: the idea

Day 1's / counts complete groups and % gives what is left over. One extra block is needed only when something is left over.

Hint 2: a first step

Start with int blocks = minutes / 25;. For 26 that is 1. Now ask what minutes % 25 is for 26 and for 50, and which of them needs one more block.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        System.out.println(blocksNeeded(26));
    }

    static int blocksNeeded(int minutes) {
        int blocks = minutes / 25;

        if (minutes % 25 > 0) {
            blocks = blocks + 1;
        }

        return blocks;
    }
}
Text
2

minutes / 25 counts the full blocks. The if adds one more only when minutes % 25 is above zero, which is why 25 and 50 stay at 1 and 2 while 10 and 26 round up. A version that always adds one fails the 0, 25 and 50 cases.

Change it and explain

The practice editor deliberately calls blocksNeeded 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.

Predict blocksNeeded(1) and blocksNeeded(75) before running them. Then use the returned value in two reports from main: one prints 2 blocks, the other multiplies by 25 to print the booked minutes. Explain why returning a number makes this reuse easier than printing inside blocksNeeded.

Was this article helpful?

Your response is saved on this device.