: You can cast any non Boolean type to any other non boolean type. You cannot
cast a boolean to any other type; you cannot cast any other type to a boolean.
In Core Java, casting primitive types involves converting one primitive data type to another. There are two types of casting: widening (implicit) and narrowing (explicit) casting.
- Widening (Implicit) Casting:
- This type of casting occurs when you are converting a smaller data type into a larger data type.
- It is done automatically by the compiler.
- There is no loss of data in widening casting because you are converting to a larger data type.
Example:
javaint intValue = 10;
long longValue = intValue; // Widening casting from int to long
- Narrowing (Explicit) Casting:
- This type of casting occurs when you are converting a larger data type into a smaller data type.
- It requires explicit casting and may result in data loss if the value is too large for the target data type.
Example:
javalong longValue = 100;
int intValue = (int) longValue; // Narrowing casting from long to int
It’s important to note that when narrowing casting is performed, there is a risk of losing precision or encountering overflow/underflow issues if the value being casted is not within the valid range of the target data type. Explicit casting is done by placing the target data type in parentheses before the variable to be casted.
Remember to be cautious while using narrowing casting, as it may lead to unexpected results or loss of data.