Back to Study Material Java

Method Overloading in Java

Method overloading allows a class to have multiple methods that share the same name but differ in their parameter lists. Java determines which version to c...

Method Overloading in Java

Defining Method Overloading

Method overloading allows a class to have multiple methods that share the same name but differ in their parameter lists. Java determines which version to call at compile time based on the number of arguments, their types, or their order. This compile-time decision is called static polymorphism or early binding, and it makes APIs cleaner because callers use one intuitive name regardless of the data types involved.

Rules for Valid Overloading To overload a method correctly, at least one of the following must differ between versions: the number of parameters, the type of at least one parameter, or the order of parameter types. Changing only the return type does not constitute overloading and will cause a compile error if the parameter lists are identical. The access modifier can differ, but that alone is not enough to distinguish overloaded methods.

How the Compiler Resolves Calls When the compiler sees a method call, it looks for an exact match first. If no exact match exists, it applies widening conversion—for example, passing an int where a long is expected. If widening still does not produce a unique match, the compiler checks for autoboxing. Finally, it considers varargs. This resolution order means you can accidentally call an unintended overload if you are not careful with your argument types.

Practical Benefits Consider a print utility. Without overloading, you would need printInt, printDouble, and printString. With overloading you write print for all three, and callers never need to remember which variant to use. The Java standard library uses this pattern extensively. System.out.println is overloaded to accept every primitive type, strings, objects, and arrays.

Code Example: class Formatter { static String format(int n) { return "int: " + n; } static String format(double d) { return "double: " + d; } static String format(String s) { return "string: " + s; } } // format(5) -> "int: 5" // format(3.14) -> "double: 3.14" // format("hi") -> "string: hi"

Interview Tip: A common exam question asks whether changing only the return type creates a valid overload. It does not. The compiler cannot determine which version to call based on return type alone because callers are not required to use the return value. Always emphasize that overloading is resolved at compile time, not runtime.