
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Method Overloading Based on the Order of Arguments in Java
In method overloading, the class can have multiple methods with the same name but the parameter list of the methods should not be the same. One way to make sure that the parameter list is different is to change the order of the arguments in the methods.
A program that demonstrates this is given as follows −
Example
class PrintValues { public void print(int val1, char val2) { System.out.println("\nThe int value is: " + val1); System.out.println("The char value is: " + val2); } public void print(char val1, int val2) { System.out.println("\nThe char value is: " + val1); System.out.println("The int value is: " + val2); } } public class Demo { public static void main(String[] args) { PrintValues obj = new PrintValues(); obj.print(15, 'A'); obj.print('P', 4); } }
Output
The int value is: 15 The char value is: A The char value is: P The int value is: 4
Now let us understand the above program.
The PrintValues class is created with two methods print() in the implementation of method overloading. The first of these takes 2 parameters of type int and type char respectively and the other takes 2 parameters of type char and type int respectively. A code snippet which demonstrates this is as follows −
class PrintValues { public void print(int val1, char val2) { System.out.println("\nThe int value is: " + val1); System.out.println("The char value is: " + val2); } public void print(char val1, int val2) { System.out.println("\nThe char value is: " + val1); System.out.println("The int value is: " + val2); } }
In the main() method, object obj of class PrintValues is created and the print() method is called two times with parameters (15, ’A’) and (‘P’, 4) respectively. A code snippet which demonstrates this is as follows:
public class Demo { public static void main(String[] args) { PrintValues obj = new PrintValues(); obj.print(15, 'A'); obj.print('P', 4); } }