What is casting?

There are two types of casting, casting between primitive numeric types and casting between object references.

Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values.

Casting between object references is used to refer to an object by a compatible class, interface, or arraytype reference.

In Java, casting refers to the process of explicitly converting a value from one data type to another. There are two types of casting in Java:

  1. Widening (Implicit) Casting: This occurs when you convert a smaller data type to a larger data type, and Java does it automatically without any explicit casting needed. For example, converting an int to a long or a float to a double is a widening conversion.
    java
    int intValue = 10;
    long longValue = intValue; // Widening (implicit) casting
  2. Narrowing (Explicit) Casting: This occurs when you convert a larger data type to a smaller data type, and it requires explicit casting because there is a possibility of losing data. For example, converting a double to an int requires explicit casting.
    java
    double doubleValue = 10.5;
    int intValue = (int) doubleValue; // Narrowing (explicit) casting

It’s important to note that narrowing casting may lead to loss of information if the value being cast cannot be represented accurately in the target data type. Therefore, it should be done carefully, and programmers need to be aware of potential data loss.