AI Hints
Home›Java Tutorial›Defining Methods, Parameters and Return Values
Java · Lesson 57 of 120

Return Values

Get an answer back.

⏱ 2 min read▶ Video at 1:11:26🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Some methods do a job, and some give back an answer. Like Math dot round, which hands back a rounded number. A return value is the answer a method gives back.

  • Do a job
  • Or give an answer
  • A return value

Returning a value

The type before the name is the return type. Square returns an int. Return sends the answer back to the caller. The call itself becomes that value, so we can store it, or use it in a sum. Void means a method returns nothing. Run it. Forty nine. Nine plus sixteen is twenty five. And ten with tax is twelve.

Main.javajava
public class Main {
    static int square(int n) {
        return n * n;
    }

    static double withTax(double price) {
        return price * 1.2;
    }

    public static void main(String[] args) {
        int s = square(7);
        System.out.println("7 squared is " + s);
        System.out.println("Sum of squares: " + (square(3) + square(4)));
        System.out.println("With tax: " + withTax(10));
    }
}
Output
7 squared is 49
Sum of squares: 25
With tax: 12.0

Returning early

Return also ends the method immediately. So once a return runs, nothing after it does. Here, each if returns early. If neither does, we reach the last line. Run it. Small, medium, and large.

Main.javajava
public class Main {
    static String sizeOf(int n) {
        if (n < 10) {
            return "small";
        }
        if (n < 100) {
            return "medium";
        }
        return "large";
    }

    public static void main(String[] args) {
        System.out.println(sizeOf(4) + " " + sizeOf(42) + " " + sizeOf(420));
    }
}
Output
small medium large

Summary

The return type says what comes back, and return sends it. Return also ends the method. Void means nothing comes back. Next, several methods with the same name.

Key takeaways
  • static int name()
  • return value;
  • void: nothing back
Next up: Overloading — same name, different inputs