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

 Live Demo

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

Updated on: 17-Jun-2020

938 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements