Type Casting
In short: The explicit (or implicit) conversion of a value from one data type to another — e.g. from int to double or vice versa.
In more detail: “Widening” (e.g. int → double) happens automatically, since no information is lost in the process. “Narrowing” (e.g. double → int) has to be explicitly forced, since precision can be lost in the process: int i = (int) 3.9; gives 3, the decimal part is cut off, not rounded.
In Depth
// Widening (automatic, no data loss):
int i = 100;
double d = i; // int -> double, works with no explicit casting
// Narrowing (has to be explicitly forced):
double price = 19.99;
int roundedDown = (int) price; // 19 - decimal places are cut off, NOT rounded
// For objects: downcasting a superclass reference back to a subclass
Object obj = "Hello"; // upcasting happens automatically
String s = (String) obj; // downcasting has to be explicit and can fail
if (obj instanceof String) { // safety check BEFORE the cast
String safe = (String) obj;
}For primitive types, Java distinguishes between “widening” (a smaller type is automatically converted into a larger one, e.g. int → long → double, since no information is guaranteed to be lost) and “narrowing” (a larger type has to fit into a smaller one, e.g. double → int), which always has to be explicitly forced with (targetType), because precision or entire values can be lost in the process. Important: (int) 19.99 does NOT round to 20, it simply cuts off the decimal places (19) — for genuine rounding, Math.round(...) is needed.
For objects (reference types), casting works on the same basic principle: “upcasting” (assigning a subclass to a superclass variable, e.g. Object obj = "text") happens automatically and is always safe. “Downcasting” (casting a more general reference back into a more specific type) has to be explicit and can fail at runtime with a ClassCastException if the object actually isn’t of the cast target type at all — which is why, before a downcast, it’s ideal to check with instanceof whether the object really has the desired type.
See also: double, byte, Non-primitive Types