Auto conversion, Widening Type Promotion or Implicit Casting – Computer Sir Ki Class


Code Learning#JAVA#3787 siteicon   siteicon   siteicon  

Auto conversion, Widening Type Promotion or Implicit Casting

Understanding rules of widening type promotions from byte->short->int->long->float->double.

Learning Objectives

  • Type conversion for widening of primitives.

Source Code

TC++ #3787

Source Code

class TypeConversionAuto
public static void main(String[] args)
byte a=127;
short b=a;
int c=b;
long d=c;
float e=d;
double f=e;
System.out.println("byte initialised a="+a);
System.out.println("byte to short b="+b);
System.out.println("short to int c="+c);
System.out.println("int to long d="+d);
System.out.println("long to float e="+e);
System.out.println("float to double f="+f);

Test it !

Run Output

byte initialised a=127
byte to short b=127
short to int c=127
int to long d=127
long to float e=127.0
float to double f=127.0

Code Understanding

byte a=127; short b=a;  int c=b; long d=c; float e=d; double f=e;
Largest byte number (8 bit positive value) is stored in a and then successfully widened to short, int, long, float and double. When long to float widening occurs, loss of precision occurs but magnitude can still be achieved. This is due to the fact long is direct storage of number in 64 bit form but float is 32 bit storage in mantissa and exponent form which can store a larger number in order of magnitude as compared to long.

System.out.println(“byte initialised a=”+a);
System.out.println(“byte to short b=”+b);
System.out.println(“short to int c=”+c);
System.out.println(“int to long d=”+d);
System.out.println(“long to float e=”+e);
System.out.println(“float to double f=”+f);
All numbers are printed.

Code Notes

  • Widening of primitives is of following types

    – byte to short, int, long, float, or double
    – short to int, long, float, or double
    – char to int, long, float, or double
    – int to long, float, or double
    – long to float or double
    – float to double

  • The type conversion document can be referred at

Suggested Filename(s):


sunmitra| Created: 6-Mar-2018 | Updated: 6-Mar-2018|