Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

3.3 Methods — returning a value

Lesson

Handing a value back

Instead of just printing, a method can return a value to whoever called it. The return type (written before the name) says what kind of value comes back — int, double, String, boolean. The return statement sends the value back and ends the method.


Worked example

int square(int n) {
    return n * n;
}

System.out.println(square(5));   // 25

The return type is int; return n * n hands back 25, which is then printed.


▶ Try it: square(int n) returns n * n. Run this, then change 5 to other numbers and re-run.



square(int n) returns n * n. What value does square(5) give back?


What is the return type of int square(int n)?


Assemble a statement that returns n squared.


True or false?


Type exactly what this program prints.

public class Main {
    static int twice(int n) {
        return n * 2;
    }
    public static void main(String[] args) {
        System.out.println(twice(6));
    }
}