- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 and type promotion in Java
Method overloading helps to create multiple methods with the same name to do similar action on a different type of parameters.
We can use type promotion in case variables are of similar type. Type promotion automatically promotes the lower range value to higher range value. For example, byte variable can be assigned to an int variable. Here byte variable will be type promoted to int. In case, we want to add two numbers which can be byte, short or int, we can use a single method. See the example below −
Example
public class Tester { public static void main(String args[]) { Tester tester = new Tester(); byte a = 1, b= 2; short c = 1, d = 2; int e = 1, f = 2; System.out.println(tester.add(a, b)); System.out.println(tester.add(c, d)); System.out.println(tester.add(e, f)); } public int add(int a, int b) { return a + b; } }
Output
3 3 3
Advertisements