Type Promotion in Java

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

package demo11;

class Demo11

{

    void subtract(int x, int y)

    {

        System.out.println(x-y);

    }

    void subtract(int x, int y, int z)

    {

        System.out.println(x-y-z);

    }

    void subtract(int x, int y, int z, int w)

    {

        System.out.println(x-y-z-w);

    }

    public static void main(String[] args)

    {

        Demo11 s = new Demo11();

        s.subtract(20, 10);

        s.subtract(60, 30, 10);

        s.subtract(90, 30, 20, 10);

    }

}

 

Output


method overloading

 

Example of Type Promotion in Java

 

Example 1

 

Type promotion is done here.

 

package demo11;

class Demo11

{

    void sum(int x, long y)

    {

        System.out.println(x+y);

    }

    void sum(int x, int y, int z)

    {

        System.out.println(x+y+z);

    }

    public static void main(String[] args)

    {

        Demo11 s = new Demo11();

        s.sum(40, 40);

        s.sum(40, 40, 40);

    }

}

 

Output


method overloading with type promotion

 

Example 2

 

No type promotion, because the datatypes match here.

 

package demo11;

class Demo11

{

    void sum(int x, int y)

    {

        System.out.println("yahoo");

    }

    void sum(long x, long y)

    {

        System.out.println("lalala");

    }

    void sum(double x, double y)

    {

        System.out.println("pppppp");

    }

    public static void main(String[] args)

    {

        Demo11 s = new Demo11();

        s.sum(40, 40);

    }

}

 

Output


no type promotion

 

Example 3

 

We cannot de-promote datatypes.

 

package demo11;

class Demo11

{

    void sum(int x, long y)

    {

        System.out.println("yahoo");

    }

    void sum(long x, int y)

    {

        System.out.println("lalala");

    }

    public static void main(String[] args)

    {

        Demo11 s = new Demo11();

        s.sum(40, 40);

    }

}

 

Output


no type promotion is done


Summary

 

This article explains type promotion in Java.

Up Next
    Ebook Download
    View all
    Learn
    View all