Type Casting
Type Casting
TYPE CASTING
1. WIDENING
2. NARROWING
WIDENING :
Byte < short < char < int < long < float < double
Example for widening :
class Widening
{
public static void main(String[] args)
{
int a=10;
float num=a; // automatically int is converted to float type
System.out.println(a);
System.out.println(num);
}
}
Output :
10
10.0
class Widening
{
public static void main(String[] args)
{
int a=10;
char c=a; // Compile time error
System.out.println(a);
System.out.println(c);
}
}
Note : It will give compile time error since we are trying to convert higher range data
type (int) to smaller range data type( char).
NARROWING :
• The process of converting higher range primitive data type into lower range
primitive data type is known as narrowing.
• In this process, there is possibility of data loss.
• Since there is possibility for data loss, compiler will not perform anything
implicitly.
• The programmer will have to explicitly(manually) perform Narrowing.
• This can be achieved with the help of type cast operator.
Byte < short < char < int < long < float < double
Example :
class Narrowing
{
public static void main(String[] args)
{
int a=10;
char ch=a; // Compile time error
System.out.println(a);
System.out.println(c);
}
}
Note : It will give compile time error since we are trying to convert higher range data
type (int) to smaller range data type( char) without type cast operator.
Type cast operator :
• It is an unary operator.
• It is used to explicitly convert one data type to another data type.
Example for narrowing :
class Narrowing
{
public static void main(String[] args)
{
int a=10;
char ch=( char ) a; //explicitly converting float to int using type cast operator
System.out.println(a);
System.out.println(c);
} Output :
} 10.0
10