Skip to content
Tutorials Center
My learning

Topics

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.

Java
int whole = (int) 3.99;       // 3
Object o = "text";
String s = (String) o;

Try it

Java Primitive casts

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.

Java Reference casts

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

Java
(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_VALUE or MAX_VALUE of the target and NaN becomes 0. Use Math.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 / b converts a first. Cast before the operation that might overflow, not after.
  • char is unsigned 16-bit, so (char) -1 is '๏ฟฟ' and (short) c can be negative.
  • Downcasts fail with ClassCastException if the object is not an instance of the target. Guard with instanceof pattern matching.
  • Generics. Casting to a parameterized type ((List<String>) obj) is an unchecked warning because type arguments are erased.
  • Boxing. You cannot cast Object directly to a different primitive than the boxed type holds; (int) obj works only for Integer.
  • Sealed and interface casts to unrelated final classes are rejected at compile time.