Type Casting in Java
Converting one data type to another data type is known as type casting.
Type Casting in Java is of two types -
- Implicit Type Casting ( Automatic Type Casting).
- Explicit Type Casting.
Implicit or Automatic Type Casting
- In this, smaller(occupying less memory) data type is converted to bigger data type which is also known as widening.
- This is done implicitly by JVM.The Lower size is widened to higher size.
- There is no data loss chance.
- It is done by compiler therefore it is known as automatic type casting.
- Example: byte b=30; int x=b; Here byte type is converted to int type.
Explicit Type Casting
- In this, bigger data type is converted to smaller data type which is also known as narrowing.
- The Higher size is narrowed to lower size.
- There is data loss chance.
- It is done by the user with the help of type cast operator i.e. ( ).
- Example: int x=30; byte b=(byte)x; Here int type is converted to byte type.