EMZETT.
Login

Type Casting

In short: The explicit or implicit conversion of a value from one data type to another — e.g. an integer into a floating-point number or vice versa.

In more detail: For implicit (“widening”) conversions, the language automatically takes care of it, for example when an int fits losslessly into a double. Explicit (“narrowing”) casting has to be requested by the programmer themselves, because information can be lost in the process — for example when a floating-point number is converted into an integer and the decimal places are dropped. Incorrect casting is a common source of error, especially when converting between very different value ranges.

In Depth

int integer = 10;
double floatingPoint = integer;    // implicit (widening) - int fits losslessly into double
 
double price = 19.99;
int roundedDown = (int) price;    // explicit (narrowing) - has to be requested
System.out.println(roundedDown);  // 19 - the decimal places are simply GONE, not rounded!

An important detail for “narrowing” casts from floating-point to integer types: it isn’t mathematically rounded, just simply truncated (towards zero) — (int) 19.99 gives 19, not 20. Anyone needing genuine rounding has to explicitly use a rounding function (e.g. Math.round()), instead of relying on the cast itself.

Besides conversion between numeric types, casting also occurs for objects within an inheritance hierarchy:

Animal a = new Dog();          // implicit: Dog "is a" Animal
Dog d = (Dog) a;            // explicit: "downcasting" back to the more specific type

An object of a subclass can implicitly be treated as its superclass type (every Dog is also an Animal) — this is safe, because a Dog can do everything an Animal can. The reverse route (explicitly casting an Animal to a Dog), by contrast, is risky: if the object at runtime actually isn’t a Dog at all, but, say, a Cat, this cast throws a runtime error. Many languages therefore offer a safe check variant (e.g. instanceof in Java), to test before casting whether it would even be allowed.

See also: byte, double, Non-primitive Types