DEV Community

PRIYA K
PRIYA K

Posted on • Edited on

Method Over Loading




Method Overloading in Java | Coding Shuttle

This blog explains everything about Method Overloading in Java, covering its rules, benefits, real-world examples, and common mistakes. It also includes constructor overloading with clear code samples to help you master compile-time polymorphism.

favicon codingshuttle.com

Java - Access Modifiers

Java access modifiers are used to specify the scope of the variables, data members, methods, classes, or constructors. These help to restrict and secure the access (or, level of access) of the data.

favicon tutorialspoint.com

1. What is Method Overloading?
When a class has two or more methods by the same name but different parameters, at the time of calling based on the parameters passed respective method is called (or respective method body will be bonded with the calling line dynamically). This mechanism is known as method overloading.
Method Overloading in Java allows a class to have multiple methods with the same name but different parameters, enabling compile-time polymorphism.

Methods can share the same name if their parameter lists differ.
Cannot overload by return type alone; parameters must differ.
The compiler chooses the most specific match when multiple methods could apply.
Enter fullscreen mode Exit fullscreen mode

Different Ways of Java Method Overloading

Method overloading can be achieved using following ways while having same name methods in a class.

Use different number of arguments
Use different type of arguments
Enter fullscreen mode Exit fullscreen mode

Invalid Ways of Java Method Overloading

Method overloading cannot be achieved using following ways while having same name methods in a class. Compiler will complain of duplicate method presence.

Using different return type
Using static and non-static methods
Enter fullscreen mode Exit fullscreen mode

Method Overloading: Different Number of Arguments

Example: Different Number of Arguments (Static Methods)
Example: Different Number of Arguments (Non Static Methods)

Method Overloading: Different Type of Arguments
Example: Different Type of Arguments

Method overloading in Java occurs when multiple methods in a class share the same name but differ in parameter type or count.
Method Overloading is a feature in Java
Method overloading in Java allows a class to have multiple methods with the exact same name but different parameter lists. It is used to implement compile-time polymorphism (also known as static polymorphism or early binding), meaning the Java compiler determines exactly which method to execute during compilation based on the arguments provided
Multiple methods can have the same name as long as the number and/or type of parameters are different.
With method overloading, multiple methods can have the same name with different parameters
Method Overloading in Java is when a class contains multiple methods with the same name but different argument lists

This concept is similar to Constructor Overloading in Java, where multiple constructors can exist within a class, each with different parameter types or counts, allowing flexible object creation.

Java determines which method to use based on the arguments passed. The compiler automatically selects the appropriate method.

Method Resolution Rules

Java follows a specific set of rules when choosing which overloaded method to call, and understanding these can help you avoid some common pitfalls.

The different ways of method overloading in Java are mentioned below:

  1. Changing the Number of Parameters

Method overloading can be achieved by changing the number of parameters when passing to different methods.

Explanation:

Two methods have the same name but different number of parameters.
Compiler selects the correct method based on how many arguments are passed.
Enter fullscreen mode Exit fullscreen mode
  1. Changing Data Types of Parameters

In many cases, methods can be considered overloaded if they have the same name but have different parameter types, methods are considered to be overloaded.

Explanation:

Methods differ in parameter types (int vs double).
Compiler matches the method based on the exact data type of arguments.
Enter fullscreen mode Exit fullscreen mode
  1. Changing the Order of Parameters

Method overloading can also be implemented by rearranging the parameters of two or more overloaded methods

Explanation:

Methods have the same name but parameter order is different.
Compiler identifies which method to call based on sequence of arguments.

Note :  There can be a hybrid overloading also where number of parameters, type of parameters and order of parameters cam change in any combination.
Enter fullscreen mode Exit fullscreen mode

What if the Exact Prototype Does Not Match?

Java tries type promotion in overloading

Convert to a higher type in the same hierarchy (e.g., byte -> int).
Convert to the next higher hierarchy if needed (e.g., int -> float).
Enter fullscreen mode Exit fullscreen mode

If no suitable method is found, it causes a compilation error

What is Method Overloading in Java?

Java allows the creation of multiple methods in a class, which can have the same names. But all the methods will be assigned with different parameters. This feature is known as Java Method Overloading. The primary significance of this feature is that it increases the readability of programs. Method Overloading is often known as Compile-time polymorphism.

Let’s delve into the Method Overloading feature with an example. In this case, we define two methods with the same name – add – but with different parameters. Utilizing the same name within the same class, including the StringBuilder Class in Java, enhances the program's readability.

where multiple methods have the same method name and same number of parameters,arguments but different parameters , different data type in the same class.
It is the one of the Polymorphism called the Compile-Time Polymorphism
class has two methods with same name (add) and return type, the only difference is the parameters they accept (one method accepts two integer variables and other accepts three integer variables).

Advantage of Method Overloading

Method overloading improves the code readability and reduces code redundancy. Method overloading also helps to achieve compile-time polymorphism.

Method overloading: Benefits

The definition of Method Overloading is highly similar to that of Constructor Overloading in Java, but they're not the same. The former is a fairly popular feature in Java, with multiple advantages. The following are some benefits of using Method Overloading:

a) Method overloading significantly improves the readability of programs.

b) The feature allows programmers to operate on tasks efficiently.

c) Using Method Overloading results in codes that look neat and compact.

d) Complex programs can be simplified using Method Overloading.

e) Codes can be reused using this feature, which helps save memory as well.

f) Since binding is accomplished in the compilation time, the execution period shortens.

g) Method Overloading can also be used on constructors, which offers you opportunities to initialise objects of a class in different ways.

h) Using Method Overloading, you can access the methods that perform related functions that use the same name, with a minor difference in the argument number or type.

How do you initiate method overloading in Java?

Method overloading can be used by changing the number of parameters or the data type.
Change in the number of parameters

One of the ways to accomplish Method Overloading is by changing the number of parameters. This is done while passing to different methods. Here is an example of changing the number of parameters while using Method Overloading in Java.

Change in the data types of arguments
Method Overloading can also be accomplished by having different parameter types with the same name.

Overloading and overriding are different in a couple of aspects. While overloading has a different number of parameters, overriding has the same. Another difference between the two is regarding the number of methods involved. Overloading requires at least two methods by the same name in a class, while overriding needs at least one method by the same name in both the parent and child classes. A similar distinction can be made when considering StringBuffer and StringBuilder; although they serve similar purposes, they differ in terms of thread safety and performance.

Overriding static methods is permitted due to its reliance on dynamic binding at runtime, while bonding of static methods occurs at compile time with static binding. The process is also known as run time polymorphism.

The main() method in Java can be overloaded. The significance of the main() method is that it is considered the starting point for the processing of Java programs. The syntax of the method is the public static void main (String[] args). The syntax never changes, although the String array argument name can be changed.

3 Ways to Overload a Method
Changing the number of parameters:void print(int a) vs void print(int a, int b)
Changing the data types of parameters:void print(int a) vs void print(double a)
Changing the order of parameters:void print(int a, String b) vs void print(String b, int a)

Critical Rules & Constraints
Return type does not matter: You cannot overload a method by changing only its return type. For example, int speed() and double speed() will throw a compile-time error if they share identical parameters.

Modifiers are ignored: Changing access modifiers (e.g., public to private) or keywords like static does not qualify as overloading if the parameters are identical.

Main method can be overloaded: Java allows you to overload the public static void main(String[] args) method, but the Java Virtual Machine (JVM) will always look for the standard String[] args signature as the starting program entry point.

Why Use Method Overloading?
Improves code readability: You do not need to create confusing, distinct names like addInt() and addDouble() for similar operations.Provides clean flexibility: It allows clean handling of diverse inputs without forcing object type conversions

If you would like to expand on this, let me know if you want to look into constructor overloading, see how Java handles type promotion when matching arguments, or compare overloading with method overriding

The methods differ by:
Number of parameters
Type of parameters
Order of parameters

Example

public class Sample{
    public static void main(String[]args){
        Sample casio = new Sample();
        casio.add(10,20);
        casio.add(10,20,30);
        casio.add();
    }
    public void add(int no1,int no2){
        System.out.println("2 arguments");
    }
    public void add(){
        System.out.println("0 arguments method");
    }
    public void add(int no1,int no2,int no3){
        System.out.println("3 arguments");
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

2.Rules of Method Overloading

Not Change the Number of Parameters

class SumExample {

    int sum(int a, int b) {
        return a + b;
    }

    int sum(int a, int b, int c) {
        return a + b + c;
    }

    public static void main(String[] args) {
        SumExample obj = new SumExample();

        System.out.println(obj.sum(10, 20));
        System.out.println(obj.sum(10, 20, 30));
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Not Change the Data Type of Parameters

class PrintExample {

    void print(int a) {
        System.out.println("Integer: " + a);
    }

    void print(String a) {
        System.out.println("String: " + a);
    }

    public static void main(String[] args) {
        PrintExample obj = new PrintExample();

        obj.print(100);
        obj.print("Java");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Not Change the Order of Parameters

class ShowExample {

    void show(int a, String b) {
        System.out.println(a + " " + b);
    }

    void show(String b, int a) {
        System.out.println(b + " " + a);
    }

    public static void main(String[] args) {
        ShowExample obj = new ShowExample();

        obj.show(10, "Java");
        obj.show("Hello", 20);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Changing only the return type is NOT allowed in Java.
Example

class Calculator {

    int multiply(int a, int b){
        return a * b;
    }

    int multiply(int a, int b, int c){
        return a * b * c;
    }

    double multiply(double a, double b){
        return a * b;
    }

    public static void main(String[] args){

        Calculator obj = new Calculator();

        System.out.println(obj.multiply(5, 4));
        System.out.println(obj.multiply(2, 3, 4));
        System.out.println(obj.multiply(2.5, 4.0));
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

3. Step-by-Step Execution
Program starts from the main() method
Object of the class is created
Method is called using the object
Java compares the arguments with method parameters
The correct overloaded method runs
Output is displayed

4.Advantage Of Method OverLoading
Keep code clean and readable
Use the same method name for similar operations
Avoid creating many method names
Make programs easier to maintain

5. Simple Real-Life Idea
Think of a mobile phone camera:

Same button → Camera
Different modes:
Photo
Video
Portrait

Same name, different behavior depending on input.

  1. Exact Match — The Most Specific Method Wins

When there’s an exact match between the argument types and a method’s parameters, Java uses this method directly.

class Example {
void print(int a) {
System.out.println("print(int) called");
}
void print(double a) {
System.out.println("print(double) called");
}

public static void main(String[] args) {
    Example ex = new Example();
    ex.print(10);    // Calls print(int)
    ex.print(10.5);  // Calls print(double)
}
Enter fullscreen mode Exit fullscreen mode

}

Output:

print(int) called
print(double) called

When print() is called with an int, Java matches it directly to print(int), and similarly for double. This is the simplest case of method resolution.

  1. Type Promotion (Widening)

When there’s no exact match, Java tries to promote the type to the next wider type in its type hierarchy, following this order:
— byte → short → int → long → float → double
— char → int

class Example {
void display(long a) {
System.out.println("display(long) called");
}
void display(double a) {
System.out.println("display(double) called");
}

public static void main(String[] args) {
    Example ex = new Example();
    ex.display(10);       // Promotes int to long and calls display(long)
    ex.display(10.5f);    // Promotes float to double and calls display(double)
}
Enter fullscreen mode Exit fullscreen mode

}

Output:

display(long) called
display(double) called

Since no int or float method exists, int promotes to long, and float promotes to double.
Become a Medium member

  1. Varargs — The Fallback Option

If there’s no exact or promotable match, Java uses a varargs method (variable-length argument list). Varargs are treated as a “catch-all” when no better match exists.

class Example {
void print(int... numbers) {
System.out.println("print(int...) called with " + numbers.length + " arguments");
}

public static void main(String[] args) {
    Example ex = new Example();
    ex.print(10);          // Calls print(int...) with 1 argument
    ex.print(10, 20);      // Calls print(int...) with 2 arguments
}
Enter fullscreen mode Exit fullscreen mode

}

Output:

print(int…) called with 1 arguments
print(int…) called with 2 arguments

Java calls print(int…) when there’s no match for (int) or (int, int). Varargs should ideally be used sparingly as they’re the least specific option.

  1. Ambiguity and Compile-Time Errors

When overloaded methods are ambiguous, Java can’t decide which one to use, leading to a compile-time error. Ambiguity usually occurs when multiple methods match the provided arguments, but none is more specific.

class Example {
void print(int a, long b) {
System.out.println("print(int, long) called");
}
void print(long a, int b) {
System.out.println("print(long, int) called");
}

public static void main(String[] args) {
    Example ex = new Example();
    ex.print(10, 20);  // Compile-time error: reference to print is ambiguous
}
Enter fullscreen mode Exit fullscreen mode

}

Error:

error: reference to print is ambiguous

Since 10, 20 can match both print(int, long) and print(long, int), the compiler doesn’t know which to choose and throws an error.

  1. Boxing and Widening Together

Java supports autoboxing (automatically converting primitives to their wrapper classes) and can combine widening with autoboxing when necessary, though this can add complexity.

class Example {
void print(Integer a) {
System.out.println("print(Integer) called");
}
void print(long a) {
System.out.println("print(long) called");
}

public static void main(String[] args) {
    Example ex = new Example();
    ex.print(10);   // Calls print(long) since widening (int → long) is preferred over autoboxing
}
Enter fullscreen mode Exit fullscreen mode

}

Output:

print(long) called

Java prioritizes widening over boxing, so int is widened to long instead of being boxed to Integer.

Summary of Method Resolution Rules

To summarize Java’s priority when selecting an overloaded method:

  1. Exact match — Java directly chooses a method that matches the argument types.
  2. Type promotion — Java promotes the argument type to the next suitable primitive type.
  3. Autoboxing — Java boxes the primitive type into its wrapper class.
  4. Varargs — As the last option, Java uses varargs if all else fails.

Method Overloading in Java

In Java, Method Overloading allows us to define multiple methods with the same name but different parameters. It is an example of compile-time polymorphism, where the correct method is selected at compile time based on the method signature.
Why Use Method Overloading?

Method overloading helps in:

Improving code readability and reusability
Making the code cleaner and more maintainable
Reducing redundancy by allowing multiple methods with the same name but different parameters
Enter fullscreen mode Exit fullscreen mode

Rules for Method Overloading

To overload a method in Java, you must follow these rules:

Same method name but different parameters (different number, type, or order of parameters)
Return type does NOT matter for method overloading (only parameters matter)
Methods can have different access modifiers
Enter fullscreen mode Exit fullscreen mode
  1. Method Overloading with Different Number of Parameters

We can overload a method by changing the number of parameters.
Example: Different Number of Parameters

class Calculator {
// Method with two parameters
static int add(int a, int b) {
return a + b;
}

// Overloaded method with three parameters
static int add(int a, int b, int c) {
return a + b + c;
}

public static void main(String[] args) {
// Calling methods with different arguments
System.out.println("Sum of 2 numbers: " + add(10, 20));
System.out.println("Sum of 3 numbers: " + add(10, 20, 30));
}
}

Output:

Sum of 2 numbers: 30
Sum of 3 numbers: 60

Explanation:

add(int, int) is called when two arguments are passed.
add(int, int, int) is called when three arguments are passed.
The correct method is selected based on the number of parameters.
Enter fullscreen mode Exit fullscreen mode
  1. Method Overloading with Different Data Types

We can also overload methods by changing the data type of parameters.
Example: Different Data Types

class Display {
// Method with an int parameter
static void show(int num) {
System.out.println("Integer: " + num);
}

// Overloaded method with a double parameter
static void show(double num) {
System.out.println("Double: " + num);
}

public static void main(String[] args) {
// Calling methods with different types of arguments
show(10); // Calls the int version
show(10.5); // Calls the double version
}
}

Output:

Integer: 10
Double: 10.5

Explanation:

show(int) is called when an integer is passed.
show(double) is called when a double is passed.
The correct method is selected based on the type of parameter.
Enter fullscreen mode Exit fullscreen mode
  1. Method Overloading with Different Order of Parameters

We can overload methods by changing the order of parameters.
Example: Different Order of Parameters

class Printer {
// Method with (String, int)
static void printDetails(String name, int age) {
System.out.println("Name: " + name + ", Age: " + age);
}

// Overloaded method with (int, String)
static void printDetails(int age, String name) {
System.out.println("Age: " + age + ", Name: " + name);
}

public static void main(String[] args) {
// Calling methods with different order of parameters
printDetails("Alice", 25);
printDetails(30, "Bob");
}
}

Output:

Name: Alice, Age: 25
Age: 30, Name: Bob

Explanation:

Java considers (String, int) and (int, String) as different method signatures.
The correct method is called based on the order of parameters.
Enter fullscreen mode Exit fullscreen mode
  1. Method Overloading with Different Return Types (Not Allowed Alone)

In Java, we cannot overload methods by changing only the return type. The compiler does not differentiate methods based on return type alone.
Example: This Will NOT Work

class Example {
// Method returning int
int add(int a, int b) {
return a + b;
}

// Overloaded method with same parameters but different return type (INVALID)
double add(int a, int b) { // Compilation Error
return a + b;
}
}

Error Message:

Error: method add(int,int) is already defined in class Example

Solution:

To overload methods, parameters must be different, not just the return type.

  1. Constructor Overloading

Just like methods, constructors can also be overloaded. This allows us to create objects with different initial values.
Example: Constructor Overloading

class Student {
String name;
int age;

// Constructor with one parameter
Student(String name) {
this.name = name;
this.age = 18; // Default age
}

// Overloaded constructor with two parameters
Student(String name, int age) {
this.name = name;
this.age = age;
}

void display() {
System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {
// Creating objects using different constructors
Student s1 = new Student("Alice");
Student s2 = new Student("Bob", 22);

s1.display();
s2.display();
Enter fullscreen mode Exit fullscreen mode

}
}

Output:

Name: Alice, Age: 18
Name: Bob, Age: 22

Explanation:

We created two constructors (Student(String) and Student(String, int)).
Depending on the arguments, the correct constructor is selected.
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

✅ Method Overloading allows multiple methods with the same name but different parameters.

✅ Methods can be overloaded by changing:

Number of parameters
Data types of parameters
Order of parameters
Enter fullscreen mode Exit fullscreen mode

✅ Return type alone does NOT differentiate overloaded methods.

✅ Constructors can also be overloaded to initialize objects differently.
Conclusion

In this blog, we learned:

What Method Overloading is and why it is useful
Different ways to overload methods in Java
How to overload constructors
Common mistakes to avoid in method overloading
Enter fullscreen mode Exit fullscreen mode

Method overloading is a key feature of Java polymorphism that makes code more readable and flexible

Top comments (0)