Syntax
returnType methodName(paramsA) { }\nreturnType methodName(paramsB) { }Examples
Overloading by Parameter Count
Multiple versions of a method accepting a different number of arguments.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(2, 3)); // 5
System.out.println(calc.add(2, 3, 4)); // 9
}
}Overloading by Parameter Type
Versions of a method that accept different types of arguments.
public class Printer {
public void display(int value) {
System.out.println("Integer: " + value);
}
public void display(String value) {
System.out.println("String: " + value);
}
public void display(double value) {
System.out.println("Double: " + value);
}
public static void main(String[] args) {
Printer p = new Printer();
p.display(42); // Integer: 42
p.display("hello"); // String: hello
p.display(3.14); // Double: 3.14
}
}Overloaded Constructors
Overloading applies to constructors too, providing multiple ways to build an object.
public class Pizza {
private String size;
private int toppingCount;
public Pizza() {
this("Medium", 0);
}
public Pizza(String size) {
this(size, 0);
}
public Pizza(String size, int toppingCount) {
this.size = size;
this.toppingCount = toppingCount;
}
public void describe() {
System.out.println(size + " pizza with " + toppingCount + " toppings");
}
}
new Pizza().describe(); // Medium pizza with 0 toppings
new Pizza("Large", 3).describe(); // Large pizza with 3 toppingsBest practices
- Only overload methods when the different versions perform genuinely similar, related operations - otherwise use distinct method names for clarity
- Avoid overloads that are ambiguous with automatic type widening (like both int and long versions), since the compiler may not resolve calls the way you expect
- Remember overload resolution happens at compile time based on the declared parameter types, not the runtime type of the arguments
- Use overloaded constructors together with this() chaining to avoid duplicating initialization logic across each version
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification