Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java casts and numeric conversion: discarded bits and checked references

Last updated: 29 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A cast requests a conversion in a specific context; narrowing a number can discard information, while narrowing a reference can fail at runtime.

Java 8+. This is a complete program using JDK classes.

Make the loss explicit

A warehouse device reports quantities in a long because it accumulates readings for months. The receiving API accepts int. A direct cast does not validate that the reading fits; it keeps the low-order bits. Math.toIntExact provides the rejecting boundary required for a quantity, rather than quietly turning a large positive reading into a negative one.

Promotion happens before assignment. Adding two int readings uses int arithmetic even when the result is assigned to long. Convert an operand before the addition or use an exact arithmetic method. The destination type cannot repair an overflow that has already occurred.

Reference casts have a separate purpose. They do not create another object or convert its fields. The runtime checks whether the referenced object is compatible with the target type. Use instanceof when the permitted branch is conditional; null passes a reference cast but still fails when subsequently dereferenced.

Use casts at boundaries

The program puts both failures next to their inputs. Its narrowed byte result is deliberate bit manipulation, not a business quantity. A serialization layer can need that operation; an inventory counter normally needs rejection. Naming the requirement matters more than making the compiler accept the line.

Working program

Java
public class QuantityConversions {
    public static void main(String[] args) {
        long accumulated = 3_000_000_000L;
        try { Math.toIntExact(accumulated); }
        catch (ArithmeticException rejected) { System.out.println("Quantity rejected"); }
        System.out.println((byte) 260);
        int measured = Integer.MAX_VALUE;
        System.out.println((long) measured + 1);
        Object receipt = "RC-81";
        System.out.println(((String) receipt).length());
        try { Integer unused = (Integer) receipt; }
        catch (ClassCastException rejected) { System.out.println("Wrong reference type"); }
    }
}

Output

Output
Quantity rejected
4
2147483648
5
Wrong reference type

Costs and boundaries

These scalar conversions require constant work and no traversal. The surrounding parser may still allocate strings or scan digits; that is a different cost. Floating-point to integer conversion has its own rules, including truncation and special values, so do not transfer the long-to-int rule to every cast.

Common Mistakes

  • Casting after integer addition is too late to prevent that addition overflowing.
  • A successful cast does not make a mutable object safe to share.
  • Do not catch ClassCastException as ordinary collection filtering; use a typed interface.

Read next

Numeric operators, Boxing boundaries.

java
casts
Storage details