Type Casting: Changing Gears

Type Casting: Changing Gears in Java: A print shop keeps a paper guillotine at the end of the bench.

The Analogy: The Override Key On The Guillotine

A print shop keeps a paper guillotine at the end of the bench. It has a fence -- a metal stop you set to the size you are cutting -- and for everything that fits inside the fence the machine is boring in the best possible way. You feed a stack of A5 sheets through a fence set for A4 and they come out exactly as they went in. Nothing is trimmed, nothing is measured, nobody signs anything. The operator does not even think of it as a conversion.

Oversize work is different. The guillotine will not refuse a sheet that is longer than the fence. It will cut it down to the fence and hand you back a perfectly clean, perfectly wrong sheet, with the excess sitting in the offcut bin underneath. To enable that, the operator turns a small key on the side of the machine. The key does not make the cut safe. It does not check anything. It exists so the shop can say that a human decided the offcut did not matter.

That is the whole of casting. Widening -- a small number into a big type -- is the stack that fits inside the fence: automatic, silent, unremarkable. Narrowing -- a big type into a small one -- needs the key, and the key is spelled (int) or (byte) or (short). Turning it does not ask Java to be careful. It tells Java that you already know what will be lost and that you accept it. Java then does exactly as instructed and says nothing at all.

The failure mode is the one every print shop knows. A sheet three millimetres too long goes through, comes back looking immaculate, and passes inspection, because the only evidence of the trim is in a bin nobody empties until Friday. The job is folded a week later and does not line up. There is a second failure that is far kinder: feed the machine something that is not paper at all -- a bound book, a steel rule -- and it jams and stops. Java has both behaviours. Narrowing a number always cuts silently. Casting one kind of object to an unrelated kind stops the program on the spot. Knowing which of the two you are doing is most of the skill.


Syntax or Core Structure

Widening happens on plain assignment with no ceremony at all. Narrowing needs the target type written in parentheses in front of the value, and that is the key being turned.

public class Casting {
    public static void main(String[] args) {
        int small = 9;
        double wide = small;
        System.out.println("wide      " + wide);

        double money = 9.78;
        int chopped = (int) money;
        System.out.println("chopped   " + chopped);

        int big = 300;
        byte tiny = (byte) big;
        System.out.println("tiny      " + tiny);

        char letter = (char) 65;
        int code = 'z';
        System.out.println("letter    " + letter);
        System.out.println("code      " + code);

        long huge = 9_000_000_000L;
        int lost = (int) huge;
        System.out.println("lost      " + lost);
    }
}

Output:

wide      9.0
chopped   9
tiny      44
letter    A
code      122
lost      410065408

Every line there is worth a moment. wide prints 9.0 rather than 9 because the value is now a double, and the printed shape of a number follows its type, not its size. chopped is 9 because .78 went into the offcut bin. tiny is the interesting one: a byte holds -128 to 127, so 300 does not fit, and Java does not clamp it to 127. It keeps the low eight bits and reads them as a byte. 300 is 100101100 in binary; the low eight bits are 00101100, which is 44.

letter and code show that char sits on the same ladder as the integers: 65 read as a character is A, and 'z' read as a number is 122. lost is the same arithmetic as tiny at a larger scale -- nine billion does not fit in an int, the low 32 bits happen to read as 410065408, and there is no warning, no exception and no log line. The only thing standing between that and a production incident is the pair of parentheses you typed.


Technical Depth: What The Cast Operator Actually Authorises

Widening and lossless are not the same list

Everyone learns that widening is safe. It is not, quite. Two of the automatic conversions round your value and ask nobody.

ConversionWritten howCan lose information
byte to intplain assignmentno
int to longplain assignmentno
int to floatplain assignmentyes, above 16777216
long to doubleplain assignmentyes, above 9007199254740992
double to intcast requiredyes, always truncates
int to bytecast requiredyes, wraps around
Object to Stringcast requiredno, but can throw
int exact = 16_777_217;
float asFloat = exact;
long big = 9_007_199_254_740_993L;
double asDouble = big;

System.out.println("int   " + exact);
System.out.println("float " + (int) asFloat);
System.out.println("long  " + big);
System.out.println("dbl   " + (long) asDouble);

Output:

int   16777217
float 16777216
long  9007199254740993
dbl   9007199254740992

A float carries 24 bits of significand, so it can count integers exactly up to 16777216 and no further; a double carries 53 bits and stops at 9007199254740992. Past those points the type still holds enormous values, it just cannot hold every one of them, and assignment quietly picks the nearest it can represent. This is why an ID or an account number should never pass through a float or a double on its way anywhere, however wide those types look.

Truncation is not rounding

A narrowing cast on a decimal always moves toward zero. It does not round, and it does not floor.

long fits = 42L;

System.out.println("cast  pos " + (int) 9.99);
System.out.println("cast  neg " + (int) -9.99);
System.out.println("round pos " + Math.round(9.99));
System.out.println("round neg " + Math.round(-9.99));
System.out.println("floor neg " + (int) Math.floor(-9.99));
System.out.println("exact     " + Math.toIntExact(fits));
try {
    Math.toIntExact(9_000_000_000L);
} catch (ArithmeticException e) {
    System.out.println("refused   " + e.getMessage());
}

Output:

cast  pos 9
cast  neg -9
round pos 10
round neg -10
floor neg -10
exact     42
refused   integer overflow

(int) -9.99 is -9, which surprises people who expect -10. Toward zero means the negative case rounds up. If you want a specific behaviour, name it: Math.round, Math.floor or Math.ceil. And for the specific job of long-to-int there is Math.toIntExact, which is the cast with the silence removed -- it throws rather than wrapping. Prefer it every time the value came from outside your program.

Where you put the cast changes the answer

int hits = 7;
int total = 20;

System.out.println("wrong " + (double) (hits / total));
System.out.println("right " + (double) hits / total);
System.out.println("also  " + hits / (double) total);

Output:

wrong 0.0
right 0.35
also  0.35

hits / total is int divided by int, which is integer division, which is 0. Casting afterwards converts a number that is already wrong. The cast has to touch an operand, so that the division itself is performed in floating point. One operand is enough -- the other is promoted to match.

The compiler's one act of leniency

There is a single exception to "narrowing needs a cast": if the value is a compile-time constant that provably fits, Java lets it through.

byte a = 100;
int n = 100;
final int m = 100;
byte d = m;
char e = 'a' + 1;

System.out.println("a " + a);
System.out.println("d " + d);
System.out.println("e " + e);
System.out.println("n " + n);

Output:

a 100
d 100
e b
n 100

byte a = 100; compiles because 100 is a literal that fits. byte d = m; compiles because m is final and initialised with a constant, which makes it a constant variable. char e = 'a' + 1; compiles because the whole expression is constant, and 98 is a valid char. But byte c = n; would not compile, because n is an ordinary variable and the compiler refuses to reason about what it might hold. The rule is worth knowing precisely, because it is the reason a line stops compiling the moment somebody deletes a final.

Casting objects is a different operation entirely

Cast kindFails howLoses data
Narrowing a primitivenever failssilently, by discarding bits
Widening a primitivenever failsoccasionally, by rounding
Reference cast, unrelated typeswill not compilenot applicable
Reference cast, related typesClassCastException at runtimenever
Unboxing a null wrapperNullPointerException at runtimenot applicable
Object boxed = "docket-118";
String text = (String) boxed;
System.out.println("length  " + text.length());

Object number = Integer.valueOf(42);
if (number instanceof String) {
    System.out.println("guarded false");
} else {
    System.out.println("guarded true");
}

try {
    String bad = (String) number;
    System.out.println("reached " + bad);
} catch (ClassCastException ex) {
    System.out.println("stopped true");
}

Output:

length  10
guarded true
stopped true

A reference cast never changes the object and never loses anything. It is a claim about what the object already is, checked at runtime, and a wrong claim stops the program. That last block prints a flag rather than ex.getMessage() on purpose: the wording of a ClassCastException message has changed between JDK releases, so printing it makes the example's output depend on which Java you happen to be running.


Real World Example: A Meter Reading Sheet That Has To Balance

A utility bills electricity. Meters report a raw pulse count that only ever goes up, so it is a long. The tariff is a whole number of pence per unit, so it is an int. The printed bill is text, because a bill is presented rather than calculated. Three types, and every boundary between them is a cast.

import java.util.Locale;

public class Billing {

    static final int PENCE_PER_UNIT = 27;
    static final long PULSES_PER_UNIT = 800L;

    static long unitsFrom(long pulses) {
        return pulses / PULSES_PER_UNIT;
    }

    static int penceFor(long units) {
        long pence = units * PENCE_PER_UNIT;
        if (pence > Integer.MAX_VALUE) {
            throw new IllegalStateException("bill too large for int pence");
        }
        return (int) pence;
    }

    static String pounds(int pence) {
        int whole = pence / 100;
        int part = pence % 100;
        return whole + "." + (part < 10 ? "0" + part : "" + part);
    }

    public static void main(String[] args) {
        String[] meters = { "M-101", "M-102", "M-103", "M-104" };
        long[] pulses = { 41_600L, 9_999L, 800_000L, 2_400L };

        int totalPence = 0;
        long droppedPulses = 0;

        for (int i = 0; i < meters.length; i++) {
            long units = unitsFrom(pulses[i]);
            int pence = penceFor(units);
            totalPence += pence;
            droppedPulses += pulses[i] % PULSES_PER_UNIT;
            System.out.println(String.format(Locale.ROOT,
                    "%-6s units %5d  pence %6d  GBP %8s",
                    meters[i], units, pence, pounds(pence)));
        }

        double avgRight = (double) totalPence / meters.length;
        double avgWrong = (double) (totalPence / meters.length);
        double unbilled = (double) droppedPulses * PENCE_PER_UNIT / PULSES_PER_UNIT;

        System.out.println("total pence  " + totalPence);
        System.out.println("total GBP    " + pounds(totalPence));
        System.out.println("avg right    " + avgRight);
        System.out.println("avg wrong    " + avgWrong);
        System.out.println("dropped      " + droppedPulses);
        System.out.println("unbilled     " + String.format(Locale.ROOT, "%.2f", unbilled));

        try {
            penceFor(100_000_000_000L);
        } catch (IllegalStateException ex) {
            System.out.println("guard        " + ex.getMessage());
        }
    }
}

Output:

M-101  units    52  pence   1404  GBP    14.04
M-102  units    12  pence    324  GBP     3.24
M-103  units  1000  pence  27000  GBP   270.00
M-104  units     3  pence     81  GBP     0.81
total pence  28809
total GBP    288.09
avg right    7202.25
avg wrong    7202.0
dropped      399
unbilled     13.47
guard        bill too large for int pence

Two casts in that program are load-bearing and the rest are scenery. The first is (int) pence inside penceFor, and the important thing about it is the line above it: the range check comes before the key is turned. That is the only shape in which a narrowing cast is defensible -- prove the value fits, then narrow. Written the other way round, return (int) pence; with the check afterwards, the check would be inspecting a number that had already wrapped and would happily pass.

The second is avgRight against avgWrong, which differ only in where the parentheses sit and disagree by a quarter of a penny per meter. (double) (totalPence / meters.length) divides 28809 by 4 as integers, gets 7202, throws away the remainder, and then dutifully converts the wrong answer to a double -- so it prints 7202.0 and looks entirely plausible. On a report of four meters the difference is invisible. On a report of four hundred thousand it is a number somebody has to reconcile.

Locale.ROOT in the two format calls is not decoration. String.format("%.2f", x) uses the JVM's default locale, and on a machine configured for most of continental Europe that produces 13,47 with a comma. The same jar then prints one thing on a developer's laptop and another inside the billing container, and the test that compares against 13.47 fails somewhere nobody can reproduce. Any formatted number that is going to be compared, stored or parsed again should name its locale explicitly.

The honest limits are larger than the program looks. unitsFrom truncates, so those 399 dropped pulses -- 13.47 pence of electricity that was genuinely supplied -- are never billed to anyone, and the bug is invisible to testing because every individual bill is arithmetically perfect. pounds is worse: it is string surgery rather than arithmetic, and for a credit note of -324 pence it computes whole as -3 and part as -24, then takes the part < 10 branch and prints -3.0-24. totalPence is an int accumulator with no guard of its own, so a run large enough to pass 21.4 million pounds wraps to a negative total and reports a refund. Real billing code keeps money in BigDecimal or in a long of minor units and never lets a double near it.


Common Mistakes

  1. Treating a narrowing cast as rounding. (int) 9.99 is 9 and (int) -9.99 is -9. The cast moves toward zero, which means it rounds down for positives and up for negatives. If you meant rounding, call Math.round.
  1. Casting the result of an integer division. (double) (hits / total) converts a number that is already 0. The cast must be applied to an operand so the division itself happens in floating point.
  1. Assuming every widening conversion is lossless. int to float and long to double are automatic but they round above 16777216 and 9007199254740992 respectively. Never route an identifier or an account number through either.
  1. Expecting a narrowing cast to clamp at the limit. (byte) 300 is 44, not 127. Java discards the high bits and reinterprets what is left; it does not saturate.
  1. Waiting for a runtime complaint. Narrowing a primitive never throws and never logs. The wrong answer downstream is the only evidence you will ever get, which is why the check has to be written by hand and written first.
  1. Confusing a primitive cast with a reference cast. (String) someObject is a runtime claim that can throw ClassCastException but cannot lose data. (int) someDouble cannot throw but always may lose data. They share a syntax and share nothing else.
  1. Reaching for a cast when you needed a parse. (int) "42" does not compile. Text becomes a number through Integer.parseInt, and a number becomes text through String.valueOf.
  1. Unboxing a wrapper that might be null. int n = someInteger; compiles cleanly and throws NullPointerException at runtime when the Integer is null. The cast or the implicit unboxing is not the bug; the missing null check is.
  1. Letting the platform locale decide your output. String.format("%.2f", x) produces 13.47 or 13,47 depending on the machine it runs on. Pass Locale.ROOT for anything that will be compared, stored or parsed again.

Best Practices

  • Prove the value fits before you narrow it. Compare against Integer.MAX_VALUE and Integer.MIN_VALUE, or let Math.toIntExact do it and throw on your behalf.
  • Put the cast on an operand, never on a completed integer division. (double) a / b is right; (double) (a / b) is a bug that type-checks.
  • Say which rounding you mean. Math.round, Math.floor and Math.ceil all state their intent in the name, and a cast states only that you accepted a truncation.
  • Accumulate in long, publish in int. Counters and running totals outgrow an int quietly; narrow once at the edge, with a check, rather than hoping.
  • Keep money out of float and double. Use an integer count of minor units, or BigDecimal, and do the formatting only at the moment of display.
  • Guard reference casts with instanceof instead of catching ClassCastException. A check is a decision; a caught exception is a decision you made too late.
  • Name a Locale in every format call whose output is compared, stored or reparsed. Locale.ROOT is the right default for machine-facing text.
  • Convert at the boundaries and use one type in between. Parse on the way in, format on the way out, and let the middle of the program be free of casts entirely.

Practice Exercises

  1. The Offcut Report: extend the billing program so it prints, per meter, the pulses that were dropped by unitsFrom and their value in pence. Then answer in a comment which meter is being under-billed and by how much per year if the same reading pattern repeats monthly.
  1. The Clamp: write static byte clampToByte(int value) that returns 127 for anything too large and -128 for anything too small, rather than wrapping. Print it beside (byte) value for the inputs 100, 200, 300 and -300 so the two behaviours sit side by side.
  1. The Credit Note: pounds(-324) currently prints -3.0-24. Rewrite the method so a negative amount prints -3.24, and prove it with the inputs 5, 50, 500, -5, -50 and -500. Then rewrite it a second time using String.format with Locale.ROOT and note which version you would rather maintain.