Java Method Overloading
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java Method Overloading

Jeevadharshan

Java Method Overloading 

Method overloading in Java allows multiple methods to share the same name while differing in their parameter lists (type, number, or order). This feature improves readability, promotes reuse, and creates cleaner APIs by grouping related functionality under a single method name. 

What Is Method Overloading?

Method overloading occurs when:
  • Methods have the same name 
  • Methods have different parameters 
  • Methods belong to the same class 
Java determines which method to call based on the method signature (name + parameter list). 

Why Use Method Overloading? 

Without overloading, you might create separate method names for similar operations: 

addInt(...) 
addDouble(...) 
addLong(...) 

With overloading, a single method name handles all variations: add(...) 

This makes code more intuitive and maintainable. 

Overloading Based on Parameter Type 

Methods can differ by parameter data types. 

Example 1: Overloading by Type 

public class OverloadTypeExample { 
static int calculate(int a, int b) { 
return a + b; 
    static double calculate(double a, double b) { 
        return a + b; 
    }

 public static void main(String[] args) { 
 
        int sumInt = calculate(10, 20); 
        double sumDouble = calculate(5.5, 2.3); 
 
        System.out.println("Integer sum: " + sumInt); 
        System.out.println("Double sum: " + sumDouble); 
    } 

Overloading Based on Number of Parameters  

Methods can also differ by how many parameters they accept. 
 
Example 2: Overloading by Parameter Count 
 
public class OverloadCountExample { 
 
    static int max(int a, int b) { 
        return (a > b) ? a : b; 
    } 
 
    static int max(int a, int b, int c) { 
        return max(max(a, b), c); 
    } 
 
    public static void main(String[] args) { 
 
        System.out.println("Max of 2: " + max(4, 9)); 
        System.out.println("Max of 3: " + max(4, 9, 7)); 
    } 
}

Overloading Based on Parameter Order 

Parameter order can also differentiate methods (though used less often). 
 
Example 3: Overloading by Order 
 
public class OverloadOrderExample { 
 
    static String format(String text, int count) { 
        return text.repeat(count); 
    } 
 
    static String format(int count, String text) { 
        return "[" + text.repeat(count) + "]"; 
    } 
 
    public static void main(String[] args) { 
 
        System.out.println(format("Hi", 3)); 
        System.out.println(format(2, "OK")); 
    } 
}

Important Rules of Method Overloading

  • Same method name 
  • Different parameter list (type, number, or order) 
  • Return type alone cannot differentiate methods
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !