Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 05 / Topic 3 of 7

Method overloading

Overloading means writing several methods with the same name but different parameter lists (different number of parameters, or different types). The compiler looks at the arguments in your call and picks the matching method — this is decided at compile time, before the program runs.

Real-world example: a finalPrice method for Asha's Store, with and without a discount.

static double finalPrice(double price) {
    return price;
}

static double finalPrice(double price, double percentOff) {
    return price - (price * percentOff / 100);
}

static double finalPrice(double price, double percentOff, boolean applyFlatCoupon) {
    double afterPercent = finalPrice(price, percentOff);
    if (applyFlatCoupon) {
        return Math.max(afterPercent - 100, 0);
    }
    return afterPercent;
}

System.out.println(finalPrice(1000.0));                 // 1000.0
System.out.println(finalPrice(1000.0, 10.0));            // 900.0
System.out.println(finalPrice(1000.0, 10.0, true));      // 800.0

The type of the arguments matters too, not just the count:

static double finalPrice(int price, int percentOff) {
    System.out.println("(int overload called)");
    return finalPrice((double) price, (double) percentOff);
}

System.out.println(finalPrice(1000, 10));
// (int overload called)
// 900.0

Overloaded methods must differ in their parameter list — the return type alone is not enough to tell two overloads apart, and the compiler rejects two methods with the same name and the same parameter types.

🔍 Going deeper: this is why System.out.println works for int, double, String, boolean, and more — println is overloaded dozens of times in the PrintStream class, one version per type you might hand it.

Full program: examples/02_discount_overloads.java.

Done here? The practice set for Part 5 — including the solutions — is on the part page.

Search the guide