In Java, Type Casting is a process of converting a variable of one data type into another.
Type casting can be categorized into two types:
- Implicit type casting
- Explicit type casting
Implicit typecasting:
It is known as widen or automatic type casting. The process to convert a small range data type variable to a large range data type is called implicit type casting.byte>>short>>int>>long>>float>>double
Example:
The following Java program initializes an int variable with a short value.
public static void main(String[] args) {
short x = 10;
int y = x;
System.out.println(y);
}
Output: 10Explicit typecasting
Explicit typecasting is also known as narrowing typecasting when a large range of data types is converted into a small range of data.double>>float>>long>>int>>short>>byte
Example
We initialize the short variable y with int x, when we try to execute, the program will crash with a “type mismatch” error. As we are trying to store large data type (int) into narrow data type variable (short).
public static void main(String[] args) {
int x = 10;
short y = x;
System.out.println(y);
}
OutputException in thread “main” java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from int to short at challenges.Hello.main(Hello.java:7)In this example, we initialize the short variable by assigning an integer variable, in the narrowing typecasting scenario; we have to explicitly typecast data.
public static void main(String[] args) {
int x = 10;
short y = (short)x;
System.out.println(y);
}
Output: 10
A yet another example of narrowing typecasting, double data is explicitly converted into a float.
public static void main(String[] args) {
double x = 10.0123456789d;
float y = (float)x;
System.out.println(y);
}
Output: 10.012345Do you know?
The data type should be compatible with conversion. A non-primitive data type cannot be transformed into a primitive data type.
The precision loss may occur in explicit typecasting.