Java Arena
Step 3 of 8

Returning from branches

A method can have several return statements, one in each branch. The first return that runs ends the method:

public class Main {
    public static void main(String[] args) {
        System.out.println(result(72));
        System.out.println(result(35));
    }

    public static String result(int points) {
        if (points >= 50) {
            return "pass";
        }
        return "fail";
    }
}
Output
pass
fail

For 72 the first return runs, and the method ends there. For 35 the if is skipped and the second return runs. No else is needed, because the method never gets past a return.

Java checks that every way through the method ends in a return. Without the last line, the method has no value to give back when the points are below 50, and it doesn't compile:

public class Main {
    public static void main(String[] args) {
        System.out.println(result(72));
    }

    public static String result(int points) {
        if (points >= 50) {
            return "pass";
        }
    }
}
What javac prints
Main.java:10: error: missing return statement
    }
    ^
1 error

Your task

Challenge 1 of 3

Write a method isAdult(int age) that returns true for an age of 18 or more, and false otherwise. The check runs System.out.println(isAdult(18)); and expects:

true

Challenge 2

Write a method sign(int number) that returns -1 for a negative number, 0 for zero and 1 for a positive number. The check runs System.out.println(sign(-8)); and expects:

-1

Challenge 3

Write a method clamp(int value, int low, int high) that keeps value inside the range from low to high: below it, return low; above it, return high; otherwise return the value itself. The check runs System.out.println(clamp(130, 0, 100)); and expects:

100