Type Casting in Java
Casting is a process of changing one type value to another type. In Java, we can cast one type of value to another type. It is known as type casting.
Example :
In Java, type casting is classified into two types,
-
- Widening Casting(Implicit)
-
- Narrowing Casting(Explicitly done)
Widening or Automatic type conversion
Automatic Type casting take place when,
- the two types are compatible
- the target type is larger than the source type
Example:
Int value 100 Long value 100 Float value 100.0
Narrowing or Explicit type conversion
When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting. If we don’t perform casting then compiler reports compile time error.
Example :
Double value 100.04 Long value 100 Int value 100
Example of Explicit Conversion
Here, we have one more example of explicit casting, double type is stored into long, long is stored into int etc.
Example for Conversion of int and double into a byte
Here, we are converting int and double type to byte type by using explicit type casting.