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.
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)); }}
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)); }}
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