Java Type Casting

Java is a statically typed language, which means that once a variable is declared with a data type, it cannot be used to store data of another data type. However, there are times when you might want to convert one data type to another. This is where type casting comes in. In Java, type casting is the process of converting one data type to another.

There are two types of casting:

  1. Widening Casting (Implicit Conversion)
  2. Narrowing Casting (Explicit Conversion)
  3. Widening Casting:

Widening casting happens automatically when you assign a smaller data type to a larger data type. This is also known as implicit conversion because it happens automatically without you having to do anything.

Example:

int num1 = 10;
double num2 = num1; // Widening casting happens automatically

In the above example, we declare an integer variable num1 and assign it a value of 10. Then we declare a double variable num2 and assign it the value of num1. Since double is a larger data type than int, widening casting happens automatically.

  1. Narrowing Casting:

Narrowing casting, also known as explicit conversion, happens when you assign a larger data type to a smaller data type. This requires you to perform an explicit cast.

Example:

double num1 = 10.5;
int num2 = (int) num1; // Narrowing casting requires an explicit cast

In the above example, we declare a double variable num1 and assign it a value of 10.5. Then we declare an integer variable num2 and assign it the value of num1, but since int is a smaller data type than double, we need to perform an explicit cast by wrapping num1 in parentheses and adding the (int) keyword before it.

Rules for Type Casting:

  1. You cannot convert a data type to an incompatible data type.

Example:

String str = "Hello";
int num = (int) str; // Error: Incompatible types

In the above example, we cannot convert a string data type to an integer data type because they are not compatible.

  1. You cannot convert a primitive data type to an object data type.

Example:

int num = 10;
Integer numObject = (Integer) num; // Error: Cannot convert primitive to object data type

In the above example, we cannot convert an int data type to an Integer object data type because they are not compatible.

  1. When converting from a floating-point data type to an integer data type, the decimal part is truncated.

Example:

double num1 = 10.5;
int num2 = (int) num1; // num2 will be 10

In the above example, the decimal part of 10.5 is truncated when it is cast to an integer data type.

In conclusion, type casting is a powerful feature of Java that allows you to convert one data type to another. It is essential to understand the different types of casting and their rules to avoid errors in your code. With the examples provided, you can get started with type casting in Java and take your programming skills to the next level.