method overloading and type promotion in Java

JavaJava Programming Java 8

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
raja
Published on 02-Feb-2018 10:19:25
Advertisements