SyntaxStudy
Sign Up
Java Method Overloading
Java Beginner 1 min read

Method Overloading

Method overloading allows a class to have multiple methods with the same name as long as their parameter lists differ in the number, type, or order of parameters. The return type alone is not sufficient to distinguish overloaded methods. The compiler selects the most specific overload that matches the argument types at compile time, a process called static dispatch. Overloading is useful for providing convenience variants of a method. For example, a print method might have overloads for int, double, and String so callers do not need to convert their values before calling. The Java standard library makes extensive use of overloading; System.out.println has ten overloads for different types. A common pitfall with overloading involves widening and autoboxing. When an exact match is not found, the compiler applies widening conversions before considering autoboxing or varargs. This can lead to surprising method selection when the argument type lies between two overloads. Keeping overloads predictable and clearly documented avoids confusion for library users.
Example
public class OverloadingDemo {

    // Overload 1: two ints
    static int multiply(int a, int b) {
        System.out.println("multiply(int, int)");
        return a * b;
    }

    // Overload 2: two doubles
    static double multiply(double a, double b) {
        System.out.println("multiply(double, double)");
        return a * b;
    }

    // Overload 3: three ints
    static int multiply(int a, int b, int c) {
        System.out.println("multiply(int, int, int)");
        return a * b * c;
    }

    // Overload 4: String repeat
    static String multiply(String s, int times) {
        System.out.println("multiply(String, int)");
        return s.repeat(times);
    }

    // Overloaded describe for different shapes
    static String describe(int side) {
        return "Square with side " + side;
    }

    static String describe(int width, int height) {
        return "Rectangle " + width + " x " + height;
    }

    static String describe(double radius) {
        return String.format("Circle with radius %.2f", radius);
    }

    public static void main(String[] args) {
        System.out.println(multiply(3, 4));           // int, int -> 12
        System.out.println(multiply(2.5, 4.0));       // double, double -> 10.0
        System.out.println(multiply(2, 3, 4));         // int, int, int -> 24
        System.out.println(multiply("ab", 3));         // String, int -> "ababab"

        System.out.println();
        System.out.println(describe(5));              // square
        System.out.println(describe(3, 7));           // rectangle
        System.out.println(describe(2.5));            // circle
    }
}