Introduction
Typecasting is a technique in which we convert one type of value into another type of value. There are two types of typecasting.
1. Narrowing
2. Widening
Narrowing:
Narrowing typecasting is also known as explicitly typecasting. In this type of casting there is a chance of data loss. Then java produces an error message “Possible loss of precession.”
To remove this error we must explicitly typecast.
- class Narrowing {
- public static void main(String… args) {
- int I;
- double d = 1.0;
- i = (int) d;
- System.out.print(i);
- }
- }
Widening:
When the lower data type is assigned to a higher data type then there is no chance of data loss. So this type of conversion is automatically done by java.
- class Widening {
- public static void main(String… args) {
- int I = 5;
- double d;
- d = i;
- System.out.print(d);
- }
- }