Java - Type Casting

Type casting in Java is the process of converting a value from one data type to another data type. There are two types of casting in Java: Widening Casting (Implicit) and Narrowing Casting (Explicit).

Widening Casting is the automatic type conversion that Java performs when a data type of lower size is assigned to a data type of a higher size. It is also known as implicit type casting. Java allows Widening Casting without explicit conversion as it guarantees no data loss.

int num1 = 100;
long num2 = num1; //Widening Casting

Narrowing Casting, on the other hand, is the manual type conversion that Java performs when a data type of higher size is assigned to a data type of lower size. It is also known as explicit type casting. Java requires explicit conversion for Narrowing Casting as it may lead to data loss.

double num1 = 10.5;
int num2 = (int) num1; //Narrowing Casting

In this example, we are casting a double data type into an integer data type. We use a set of parentheses with the data type to which we want to cast the value.

It's important to note that Narrowing Casting may lead to loss of data if the value is larger than the maximum value allowed for the data type.