Task 5 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 — void vs return

Lesson

Print vs return

A void method does something (like printing) but gives back no value — you can't store its result. A method with a return type gives back a value you can reuse. Rule of thumb: if the caller needs the result later, return it; if you only want to show it, printing is fine.


Worked example

void printDouble(int n) {      // prints, returns nothing
    System.out.println(n * 2);
}
int doubleOf(int n) {          // returns the value
    return n * 2;
}

printDouble(5);                // prints 10, nothing to reuse
int x = doubleOf(5);           // x is 10 — can be reused
System.out.println(x + 1);     // 11

▶ Try it: both methods are defined for you. Run this — the void one just prints, but the returned value can be stored and used again (here, + 1).



Which method gives back a value you can store and reuse?


A void method prints its result. Can you store that result in a variable?


Sort each method by whether it returns a value or returns nothing.


True or false?


Type exactly what this program prints.

public class Main {
    static void showIt(int n) {
        System.out.println(n);
    }
    static int giveIt(int n) {
        return n;
    }
    public static void main(String[] args) {
        showIt(3);
        int v = giveIt(4);
        System.out.println(v + 1);
    }
}