← Back to Core Java Course | Chapter 5: Methods & Arrays | Lesson 4 of 10

Java Method Overloading

Overloading by Parameter Count

Overloading lets several methods share the exact same name as long as their parameter lists differ -- here, differing purely in how many parameters each version accepts, like add(int, int) versus add(int, int, int).

Example: Overloading by Parameter Count

java
public class Main {
	static int add(int a, int b) {
		return a + b;
	}
	static int add(int a, int b, int c) {
		return a + b + c;
	}
	public static void main(String[] args) {
		System.out.println(add(1, 2));
		System.out.println(add(1, 2, 3));
	}
}

Overloading by Parameter Type

You can also overload by keeping the same parameter count but changing the types, like add(int, int) versus add(double, double), letting one method name handle several different kinds of input naturally.

Example: Overloading by Parameter Type

java
public class Main {
	static int add(int a, int b) {
		return a + b;
	}
	static double add(double a, double b) {
		return a + b;
	}
	public static void main(String[] args) {
		System.out.println(add(1, 2));
		System.out.println(add(1.5, 2.5));
	}
}

Overloading by Parameter Order

Even keeping the same types and count but swapping their order, like process(String, int) versus process(int, String), counts as a distinct, valid overload as far as the compiler is concerned.

Example: Overloading by Parameter Order

java
public class Main {
	static void process(String s, int n) {
		System.out.println(s + n);
	}
	static void process(int n, String s) {
		System.out.println(n + s);
	}
	public static void main(String[] args) {
		process("Item", 5);
		process(5, "Item");
	}
}

Automatic Type Promotion

When a call doesn't exactly match any overload's parameter types, Java automatically widens the arguments (like int to double) to find the closest compatible version rather than failing to compile.

Example: Automatic Type Promotion

java
public class Main {
	static double add(double a, double b) {
		return a + b;
	}
	public static void main(String[] args) {
		System.out.println(add(2, 3)); // ints widened to double
	}
}

Best Practices in Overloading

Overloads should all represent the same underlying operation with different inputs -- using the same method name for genuinely unrelated behaviors defeats the purpose and makes the API confusing to use correctly.

Example: Best Practices in Overloading

java
public class Main {
	static int add(int a, int b) {
		return a + b;
	}
	static double add(double a, double b) {
		return a + b; // same operation, different input types
	}
	public static void main(String[] args) {
		System.out.println(add(2, 3));
		System.out.println(add(2.0, 3.0));
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.