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
|
Run Output
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.
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
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
Suggested Filename(s): TypeConversionAuto.java
sunmitra| Created: 6-Mar-2018 | Updated: 6-Mar-2018|