Java Reference ยท Operators
Casting in Java
Reference for the Java cast operator: widening and narrowing primitive casts, truncation and wrapping rules, reference casts and ClassCastException.
A cast, written (Type) expression, converts a value to another type. For primitives it changes the representation of the number; for references it tells the compiler to treat an object as a more specific type and checks that at run time.
Widening conversions (int to long, float to double, subclass to superclass) happen automatically. Narrowing conversions can lose information and need an explicit cast.
int whole = (int) 3.99; // 3 Object o = "text"; String s = (String) o;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
(TargetType) expression
| Kind | Examples | Check |
|---|---|---|
| Widening primitive | long l = intValue; |
none needed; never fails (may lose low-order precision for int or long to float) |
| Narrowing primitive | (int) d, (byte) i |
explicit; never throws |
| Upcast | Animal a = dog; |
implicit |
| Downcast | (Dog) animal |
run time; may throw ClassCastException |
Usage notes
- Float to integer: the fraction is discarded (truncation toward zero). Out-of-range values clamp to
MIN_VALUEorMAX_VALUEof the target andNaNbecomes0. UseMath.round()to round. - Integer to narrower integer: only the low-order bits are kept, so the value wraps. Use
Math.toIntExact()to fail loudly. - Cast precedence. A cast binds tighter than
*and/:(double) a / bconvertsafirst. Cast before the operation that might overflow, not after. charis unsigned 16-bit, so(char) -1is'๏ฟฟ'and(short) ccan be negative.- Downcasts fail with
ClassCastExceptionif the object is not an instance of the target. Guard withinstanceofpattern matching. - Generics. Casting to a parameterized type (
(List<String>) obj) is an unchecked warning because type arguments are erased. - Boxing. You cannot cast
Objectdirectly to a different primitive than the boxed type holds;(int) objworks only forInteger. - Sealed and interface casts to unrelated final classes are rejected at compile time.