Java Type Casting

In Java, type casting is the process of converting one data type to another. There are two types of casting in Java: implicit casting and explicit casting.

Implicit casting, also known as widening conversion, is the process of converting a lower type to a higher type. This is done automatically by the compiler, and it does not require any special syntax. For example, if you assign an int value to a long variable, the int value will be automatically converted to a long value.

Here is an example of implicit casting:

refe‮i:ot r‬giftidea.com
int x = 10;
long y = x; // implicit casting from int to long

In this example, the int value 10 is implicitly cast to a long value and assigned to the y variable.

Explicit casting, also known as narrowing conversion, is the process of converting a higher type to a lower type. This requires a cast operator, which is denoted by enclosing the target type in parentheses before the value being cast. Explicit casting may result in loss of precision, so it should be used with care.

Here is an example of explicit casting:

double d = 10.5;
int i = (int) d; // explicit casting from double to int

In this example, the double value 10.5 is explicitly cast to an int value and assigned to the i variable. Note that the decimal part of the double value is truncated in the conversion.

It is important to note that not all types can be cast to one another. For example, you cannot cast a String to an int or a boolean to a double. If you try to cast incompatible types, a ClassCastException will be thrown at runtime. Therefore, you should always check the compatibility of the types before performing any type casting.