Java Casting - Converting Variable Data Types

Casting

Converting a data type is called casting, or type casting.

(type)var
  type: data type
  var: variable name

General Type Casting

First, with primitive types, a smaller type can be assigned to a larger type, such as assigning an int value to a long type. A larger type can contain a smaller one. This is called widening conversion, or implicit type conversion.

Widening Conversion

int i = 10;
double d = i;
long l = i;
float f = 3.14f;
d = f;

However, the reverse, narrowing conversion or explicit type conversion, is not possible as-is. A long value cannot always be stored in an int type.
Therefore, the long value must be explicitly cast to int. For casting, add only (typeName) immediately before the target variable.

Narrow Conversion

public class Cast {
    public static void main(String[] args) {
        long l = 50;
        int i = (int) l;
        System.out.println(1 + i);
    }
}

Class and Interface Casting

Likewise, class and interface type values can also be cast. A class or interface type can be cast when the value being assigned is a derived class or implementation of the assignment destination type.

For example, if the Hamster class is a subclass of the Animal class, the following cast is possible.

Animal a = new Hamster();
Hamster h = (Hamster) a;

However, code like the following is not possible.

Animal c = new Cat();
Hamster h = (Hamster) c; // casting error

This is because variable c is of type Animal, but its actual object is Cat.
To prevent this kind of error, use the instanceof operator. The instanceof operator determines whether an object is an instance of the specified class or superclass. In class type casting, you can determine the actual type in advance with instanceof and then cast safely.

Animal c = new Cat();
if (c instanceof Hamster) {
    Hamster h = (Hamster) c;
}