Return Values & Overloading
Return statements, early returns, and method overloading by parameter count and type. Includes varargs and overload selection demos.
Overview
Goal: Master return statements and method overloading. You will see early returns (guard clauses), overloads by count and by type, and a short varargs demo.
Return & guard
Return sends a value back to the caller and ends the method. Guard clauses (early return) keep code simple by handling special cases first.
public class Main {
// Double an integer and return the result
static int doubleIt(int x) {
return x * 2;
}
// Return a label using a simple early-return pattern (guard clause)
static String parity(int n) {
if (n % 2 == 0) {
return "even"; // early return ends the method here
}
return "odd"; // otherwise this path executes
}
public static void main(String[] args) {
System.out.println("doubleIt(7) = " + doubleIt(7));
System.out.println("parity(10) = " + parity(10));
System.out.println("parity(11) = " + parity(11));
}
}
All lessons in this course
- Defining Methods & Parameters
- Return Values & Overloading
- Scope & Lifetime