Introduction

Type promotion is done while doing method overloading in Java. When the datatype is not the same then we promote one datatype to another datatype. We cannot de-promote one datatype to another datatype.
type promotion
According to the figure:
  • byte can be promoted to <byte - short - int - long - float - double>.
  • short can be promoted to <short - int - long - float - double>.
  • int can be promoted to <int - long - float - double>.
  • long can be promoted to <long - float - double>.
  • char can be promoted to <char - int - long - float - double>.
  • float can be promoted to <float - double>.

Method Overloading in Java

In Java, when a class has multiple methods with the same name but have different parameters, it is known as method overloading.
Example
  1. package demo11;
  2. class Demo11
  3. {
  4. void subtract(int x, int y)
  5. {
  6. System.out.println(x-y);
  7. }
  8. void subtract(int x, int y, int z)
  9. {
  10. System.out.println(x-y-z);
  11. }
  12. void subtract(int x, int y, int z, int w)
  13. {
  14. System.out.println(x-y-z-w);
  15. }
  16. public static void main(String[] args)
  17. {
  18. Demo11 s = new Demo11();
  19. s.subtract(20, 10);
  20. s.subtract(60, 30, 10);
  21. s.subtract(90, 30, 20, 10);
  22. }
  23. }
Output
method overloading

Example of Type Promotion in Java

Example 1
Type promotion is done here.
  1. package demo11;
  2. class Demo11
  3. {
  4. void sum(int x, long y)
  5. {
  6. System.out.println(x+y);
  7. }
  8. void sum(int x, int y, int z)
  9. {
  10. System.out.println(x+y+z);
  11. }
  12. public static void main(String[] args)
  13. {
  14. Demo11 s = new Demo11();
  15. s.sum(40, 40);
  16. s.sum(40, 40, 40);
  17. }
  18. }
Output
method overloading with type promotion
Example 2
No type promotion, because the datatypes match here.
  1. package demo11;
  2. class Demo11
  3. {
  4. void sum(int x, int y)
  5. {
  6. System.out.println("yahoo");
  7. }
  8. void sum(long x, long y)
  9. {
  10. System.out.println("lalala");
  11. }
  12. void sum(double x, double y)
  13. {
  14. System.out.println("pppppp");
  15. }
  16. public static void main(String[] args)
  17. {
  18. Demo11 s = new Demo11();
  19. s.sum(40, 40);
  20. }
  21. }
Output
no type promotion
Example 3
We cannot de-promote datatypes.
  1. package demo11;
  2. class Demo11
  3. {
  4. void sum(int x, long y)
  5. {
  6. System.out.println("yahoo");
  7. }
  8. void sum(long x, int y)
  9. {
  10. System.out.println("lalala");
  11. }
  12. public static void main(String[] args)
  13. {
  14. Demo11 s = new Demo11();
  15. s.sum(40, 40);
  16. }
  17. }
Output
no type promotion is done
Summary
This article explains type promotion in Java.