In Java, 'type casting' refers to the process of converting a variable from one data type to another. This is often necessary when you want to perform operations on different data types or when you need to store a value in a variable of a different type.
There are two main types of type casting in Java:
-
Implicit Casting (Widening Conversion): This occurs when a smaller data type is automatically converted to a larger data type. For example, converting an
intto adoubledoes not require explicit casting because it is safe and does not result in data loss.int intValue = 10; double doubleValue = intValue; // Implicit casting -
Explicit Casting (Narrowing Conversion): This occurs when a larger data type is converted to a smaller data type. This requires explicit casting because it can lead to data loss. For example, converting a
doubleto anintrequires casting.double doubleValue = 9.78; int intValue = (int) doubleValue; // Explicit casting
In summary, type casting allows you to convert between different data types, either implicitly or explicitly, depending on the direction of the conversion.
