Type Casting
- Eclipse: Oxygen
- Java: 1.8
In Java, Type Casting is a process of converting a variable of one data type into another.
Typecasting is of two types:
- Implicit typecasting.
- Explicit typecasting.
Implicit typecasting
Implicit type casting is also known as Widening or Automatic typecasting. When a small range data type variable is converted into a large range data type, The process is called implicit typecasting.
Example:
we initialize an int variable with a short value.
1 2 3 4 5 |
public static void main(String[] args) { short x = 10; int y = x; System.out.println(y); } |
Output
1 |
10 |
Explicit typecasting
Explicit typecasting is also known as narrowing typecasting. When a large range data type is converted into small range data.
Example
We initialize the short variable y with int x, when we try to execute, the program will crash with “type mismatch” error. As we are trying to store large data type (int) into smaller data type variable (short).
1 2 3 4 5 |
public static void main(String[] args) { int x = 10; short y = x; System.out.println(y); } |
Output
1 2 3 4 5 |
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to short at challanges.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.
1 2 3 4 5 |
public static void main(String[] args) { int x = 10; short y = (short)x; System.out.println(y); } |
Output
1 |
10 |
A yet another example of narrowing typecasting, double data is explicitly converted into float.
1 2 3 4 5 |
public static void main(String[] args) { double x = 10.0123456789d; float y = (float)x; System.out.println(y); } |
Output
1 |
10.012345 |
Do you know?
- Data type should be compatible for conversion. A non-primitive data type cannot be converted into a primitive type.
- The precision loss may happen in Explicit typecasting.
Contributed by: Poonam Tomar