Java Arena
Step 1 of 8

Returning a value

The methods so far did their work and gave nothing back: they were void. A method can instead return a value to the code that called it. The value's type goes where void was, and a return statement says what to give back:

public class Main {
    public static void main(String[] args) {
        int weeks = 3;
        int days = weeks * daysInWeek();
        System.out.println(weeks + " weeks is " + days + " days");
        System.out.println(daysInWeek());
    }

    public static int daysInWeek() {
        return 7;
    }
}
Output
3 weeks is 21 days
7
  • public static int daysInWeek() says the method returns an int.
  • return 7; ends the method and hands 7 back to the call.
  • The call daysInWeek() then stands for that value, anywhere a value can go: in a calculation, in a print line, or stored in a variable (int d = daysInWeek();).

A call whose value isn't used, like daysInWeek(); on a line of its own, runs the method, and the value is simply lost.

return ends the method

Nothing after a return runs, and Java refuses code that could never run:

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

    public static int daysInWeek() {
        return 7;
        System.out.println("Counted the days");
    }
}
What javac prints
Main.java:8: error: unreachable statement
        System.out.println("Counted the days");
        ^
1 error

A void method can use a plain return; to stop early.

Your task

Challenge 1 of 3

Fill in the blanks, so luckyNumber returns 7. The check runs System.out.println(luckyNumber()); and expects:

7

Challenge 2

Write a method favouriteLanguage() that returns the String Java. The check stores what it returns and prints it in a sentence:

I like Java

Challenge 3

This method should print Checked! and then return whether 10 is more than 3, but it doesn't compile. Fix it, keeping both lines. The check runs System.out.println(isBigger()); and expects:

Checked!
true