Understanding Type Casting
➢Converting one data type into another data type is
called casting.
➢In general there are two types of casting procedures.
✓ Implicit Type Casting
✓ Explicit Type Casting
Implicit Type Casting:
➢ Converting smaller data type to larger data types is called
“Implicit Type Casting”.
➢ It is also known as Widening or Casting-Upwards.
➢ There is no lose of information in this type casting.
byte -> short, int, long, float, double
short -> int, long, float, double
char -> int, long, float, double
int -> long, float, double
long -> float, double
float -> double
Explicit Type Casting
Converting larger data type to smaller data types is called “Explicit
Type Casting”.
It is also known as Narrowing or Casting-Downwards.
There may be a chance of lose of information in this type casting.
<Destination DataType> <variableName>=(DataType) <SourceType>
Ex: int i=90;
byte b = (byte)i;
byte -> char
short -> byte, char
char -> byte, short
int -> byte, short, char
long -> byte, short, char, int
float -> byte, short, char, int, long
double -> byte, short, char, int, long, float
In casting what happens if source variable has value
greater than the destination variable type range?
We will not get any compile time error or runtime error,
assignment will be performed by reducing its value in the
range of destination variable type range.
We can know the value by using the below formula
[minimumRange + (result - maximumRange - 1)]