• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Classes » Method Overloading in Java with Example
Next →
← Prev

Method Overloading in Java with Example

By Dinesh Thakur

Method Overloading: When multiple methods in the same class with same name, having different functions or types of parameters, it is known as Method Overloading. When an overloaded method is invoked, it is the responsibility of the compiler to select the appropriate overloaded method based on the number of argument(s) passed and if the numbers of argument(s) are same then depending upon the type of argument(s) passed to the method. Thus, the key to method overloading is a method’s parameter list. A method’s return type is not enough to distinguish between two overloaded methods. If the compiler detects two methods declarations with the same name and parameter list but different return types then it will generate an error.

When you work with a Java class library, you often encounter classes that have numerous methods with the same name. We have already being using this aspect of the language implicitly when displaying text using a variety of println) method. For example

System.out.println(“Hello Java”);

System.out.println (59); //displays int

System.out.println(true); //displays boolean

System.out.println(31.37); //displays double

System.out.println(); //no parameter

Although all these methods have the same name (println) but take different parameter list. The first takes a String, the second takes a int, third takes a boolean, fourth takes a double and fifth takes no parameter at all. Thus, println ()method is overloaded.

Method overloading is useful when you want to create a collection of methods that perform closely related functions under different conditions. These conditions are typically embodied in the parameters passed to each version of the method.

In order to understand the concept of method overloading, let us consider an example of a method that is used to calculate sum of two numbers. The method definition of method sumlnt ( ) is given

void sumInt(int x,int y) {
   int z=x+y;
   System.out.println (“Sum = “+z);
}

The above method when used in the program will calculate the sum of two integer numbers. Now suppose the we also want to calculate the sum of 2 double numbers in the same program. To solve this problem, we need to make a new method with different name and double
type parameters. The method header of this new method sumDouble () is
void sumDouble(double,double);
This will not cause any problem as we have two methods to keep track off. Now suppose that. we also want to calculate the sum of two float, long , characters in the same program. To do this, we need to make different functions with different names and different type of parameters. So, the method header of all these methods are shown below.

void sumInt (int,int) ;
void sumFloat(float,float);
void sumLong (long, long) ;
void sumChar(char,char);
void sumDouble(double,double);

It is now necessary to remember five different method names that actually perform the same related operations of calculating sum of two numbers. Maintaining, using and understanding such methods in the program becomes complex for the programmer. A better solution to the above problem is to use the concept of method overloading which relieves the programmer from this complexity by providing the facility to give the same name for multiple methods that perform similar related operations provided each differs in the number or type of its parameters. The following program illustrates how the above problem can be solved using the concept of method overloading.

/*program that calculate sum of two numbers of different types using concept of method overloading */

class SumTwoNum
{
     void sum(int x, int y)
     {
        System.out.println("Sum of Two Integer Numbers : " + (x+y));
     }
     void sum(double x,double y)
     {
        System.out.println("Sum of Two Double Numbers : " + (x+y));
     }
     void sum(char x,char y)
     {
        System.out.println("Sum of Two Characters are : " + (x+y)); 
     }
}
  public class MethodOverloading
  {
     public static void main(String[] args)
     {
         SumTwoNum obj = new SumTwoNum();
         obj.sum(10,20);   //call sum method with int parameter
         obj.sum(7.52,8.14); //call sum method with double parameters
         obj.sum('A','B'); //call sum method with char parameters
     }
  }

Method Overloading in Java with Example

In the above program, three methods are defined and invoked which have the same name sum () but differ only in their parameter types (int, double and char). For each call of the method, the compiler chooses the appropriate method by comparing the types of the arguments in the call against the parameter list of each defined method. So when the statement obj.sum (7.52, 8.14); is executed, the compiler invokes the method which takes double type parameters, as seen in output.

The above example shows the concept of method overloading in which multiple methods with the same name and same number of parameters differ only in their data types. The compiler can also distinguish the multiple methods with same name by different number of parameters of the method. This can be illustrated with the help of following program.

Program to show the concept of method overloading to calculate area where same name methods differ in number of parameters?

/*program that calculate area of different shapes in which data types are same but difference in number of parameters using concept of method overloading */

class AreaShape {
   void area(int x) {
      System.out.println(“Area of square is = “ + (x*x));
   }
   void area(int x,int y) {
       System.out.println(“Area. of rectangle is = “ + (x*y))
   }
   void area(int x,int y,int z) {
doub1e s=(x+y+z)/2;
double triArea;
triArea = Math.sqrt(s*(s–x)*(s–y)*(s–z));
      System.out.println(“Area of triangle is = “ + triArea);
   }
}
public class AreaOverload {
   public static void main(String[] args) {
AreaShape obj = new AreaShape();
obj.area(10); //Call area(int x)
obj.area(5,6); //Call area(int x,int y)
obj.area(4,5,6); //Call area(int x,int y,int z)
   }
}
Output : Area of square is = 100
Area of rectangle is = 30
Area of triangle is = 6.48074069840786

Explaination: The above program is used to calculate the area of the square, rectangle and triangle. For this, three methods are declared and called separately. Each method has the same name area but differs only in the number of parameters. When the statement obj.area (10) ; is executed, the compiler invokes the method which contains only one parameter for calculating area of square. Now on execution of the statement obj. area (5, 6); the method area () with two parameters is invoked for calculating the area of rectangle. Similarly, the next call invokes method with three parameters.

Advantages of Method Overloading

The advantages of method overloading are:

1. We need to remember single name instead of multiple names of the methods that perform similar type of operations. This helps in reducing the complexity of making large programs.

2. Overloaded methods that perform similar tasks can make complex programs more readable, understandable and easy to debug.

3. Maintainability of the program becomes easier.

Method overloading is a powerful tool for creating group of related methods that only differ in the type of data sent to it. However, if not used properly such as using methods with same name for different purposes can cause considerable confusion which leads to additional overhead in terms of maintainability.
For Example: Methods performing various arithmetic operations like addition, subtraction, multiplication, division should not be overloaded with same named functions as they perform different unrelated operations ..
If the methods differ only in the return type then they are not considered as overloaded methods and hence the compiler generates an error message. This is because it is not possible for the compiler to determine which version of the method to call.

You’ll also like:

  1. Function Overloading and Method Overloading in Java
  2. Example of Method Overloading in Java
  3. Java Example for Method Overloading
  4. Constructor Overloading in Java with Example
  5. What is Function Overloading and Operator Overloading
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW