- Prerequisites
- 3.1 Primitive Types · 2.4 Operators
- Covers
- Widening · Narrowing · Explicit casting · Numeric promotion · Overflow
- Related
- 3.5 Wrapper Classes · 6.3 Polymorphism (upcasting and downcasting)
On this page
1Concept / Definition
A type conversion turns a value of one type into a value of another. Java performs some conversions automatically — those that cannot lose the magnitude of a value — and requires an explicit cast for the rest. Understanding exactly which conversions are automatic, and what an explicit one does to the bits, prevents a whole family of silent data-corruption bugs.
2Why It Exists
Programs constantly move values between types: an int count into a long total, a double average into an int for display, a byte from a file into an int for arithmetic, an Object from a collection back to its real class. C converts almost all of these silently, including the ones that lose data. Java draws a line: conversions that keep the magnitude of a value happen automatically, and every conversion that may lose information needs an explicit cast.
The cast is therefore a marker in the source that says "information may be lost here", and a reviewer can search for it. For references the same idea applies the other way round: a cast does not convert the object at all, it asks the JVM to check that the object already is of the expected type. The remaining traps, such as precision lost in widening and overflow before widening, are the cases where no cast is required and so nothing in the source warns the reader.
3Core Concepts
Widening
A widening primitive conversion goes to a type with a larger range and happens automatically in assignment, method calls and arithmetic. It never loses the magnitude of a value, but int or long to float, and long to double, can lose precision in the low digits.

Narrowing
A narrowing conversion goes to a type with a smaller range, and requires an explicit cast. Between integer types it simply discards the high-order bits, so (byte) 300 is 44 and (int) 3_000_000_000L is negative. From floating point to an integer type the value is truncated toward zero and saturated: NaN becomes 0, and values beyond the range become the minimum or maximum of the target type.

Explicit casting
A cast (Type) expression requests a conversion. For primitives it produces a new value, as above. For references it produces no new object — it changes only the static type through which the object is viewed, and the JVM checks at run time that the object really is of that type, throwing ClassCastException if not. Upcasting (to a supertype) is implicit and always safe; downcasting (to a subtype) needs a cast or, better, pattern matching (2.4).

Numeric promotion
Before arithmetic, the operands of binary operators are promoted to a common type. byte, short and char are always promoted at least to int, so byte + byte is an int. Unary -, + and ~ promote smaller types to int as well.

Overflow
Integer arithmetic that exceeds the range of its type wraps around silently (3.1). The subtle case is overflow that happens before widening: in long ms = days * 24 * 60 * 60 * 1000; with int days, the multiplication is done in int and overflows before the result is widened to long. Floating-point arithmetic does not wrap; it overflows to infinity.
4How It Works Internally
javac compiles each primitive conversion to one JVM instruction (Figure 5). The rules in section 3 are simply what these instructions do: i2b keeps the low 8 bits and sign-extends them, l2i keeps the low 32, and d2i truncates toward zero, maps NaN to 0 and saturates out-of-range values, as the JVM specification requires. i2l and i2d are exact; i2f, l2f and l2d round to the nearest representable value, which is how a widening conversion can lose digits.

Two cases never reach these instructions. A cast of a constant, such as (byte) 300, is evaluated by javac, and the class file simply contains 44. And an assignment such as byte b = 10; compiles without a cast because the JLS allows implicit narrowing of a constant expression whose value fits in the target type; byte b = i; with a variable i does not (Q9). A reference cast compiles to checkcast, which creates nothing: it compares the object's class with the target type and throws ClassCastException if it does not match. A pattern such as o instanceof String s compiles to an instanceof test followed by the same checkcast, which can then never fail.
5APIs / Features / Syntax
The cast operator has no way to report a loss. These methods convert explicitly and either fail loudly or round in a defined way:
| Method | Behaviour |
|---|---|
| Math.toIntExact(long) | Returns the int, or throws ArithmeticException if it does not fit |
| Math.addExact, multiplyExact, negateExact | Arithmetic that throws instead of wrapping |
| Math.round, floor, ceil, rint | Rounding with a defined rule (round: half up towards positive infinity) |
| BigDecimal.setScale(n, RoundingMode) | Rounding of decimal amounts with an explicit mode |
| BigDecimal.intValueExact(), longValueExact() | Convert, throwing if there is a fraction or overflow |
| Byte.toUnsignedInt, Integer.toUnsignedLong | Read a signed value as unsigned without sign extension |
| Number.intValue(), longValue() | Narrowing without any check: same as a cast |
| Class.cast(o), instanceof pattern | Checked reference conversion; the pattern avoids the exception |
6Practical Examples
Example 1 — Conversions and their results
byte b = (byte) 300; // 44: high bits discarded
int i = (int) 3_000_000_000L; // -1294967296
int t = (int) 3.99; // 3: truncation toward zero
int s = (int) 3.9e10; // 2147483647: saturates at Integer.MAX_VALUE
int n = (int) Double.NaN; // 0
float f = 16_777_217; // widening loses precision: 1.6777216E7
long big = 123_456_789_123L;
double d = big; // fine for this value; very large longs lose digits
int days = 30;
long wrong = days * 24 * 60 * 60 * 1000; // -1702967296: int overflow first
long right = days * 24L * 60 * 60 * 1000; // 2592000000: long from the start
long safest = Math.multiplyExact(days, 86_400_000L);
Object o = "text";
if (o instanceof String str) { … } // safe downcast with a pattern
int len = Math.toIntExact(someLong); // throws if the long does not fitEvery value in the comments is what the kit class Conversions prints.
Example 2 — Mini program: a usage bill with three conversion bugs
Problem. A cloud service bills data transfer per GB for a 31-day month. The first version of the billing code has three conversion bugs; none of them causes an exception.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class UsageBill {
static final long GB = 1L << 30;
public static void main(String[] args) {
int days = 31;
long bytes = 5_368_709_120L; // 5 GB transferred
double ratePerGb = 0.085; // USD per GB
// Buggy version
long periodMs = days * 24 * 60 * 60 * 1000; // bug 1: overflows in int
int size = (int) bytes; // bug 2: keeps low 32 bits
int cents = (int) (size / (double) GB * ratePerGb * 100); // bug 3
System.out.println("buggy: period=" + periodMs + " ms, size=" + size
+ ", cents=" + cents);
// Fixed version
long periodOk = Math.multiplyExact(days, 86_400_000L);
BigDecimal amount = BigDecimal.valueOf(bytes) // keep long end to end
.divide(BigDecimal.valueOf(GB)) // exact: 5
.multiply(new BigDecimal("0.085"))
.setScale(2, RoundingMode.HALF_UP); // round, do not truncate
System.out.println("fixed: period=" + periodOk + " ms, size=" + bytes
+ ", amount=" + amount);
try {
Math.toIntExact(bytes);
} catch (ArithmeticException e) {
System.out.println("toIntExact(5 GB): " + e.getMessage());
}
}
}buggy: period=-1616567296 ms, size=1073741824, cents=8
fixed: period=2678400000 ms, size=5368709120, amount=0.43
toIntExact(5 GB): integer overflowWhy it behaves this way. Bug 1: days * 24 * 60 * 60 * 1000 is evaluated in int and overflows at 2,678,400,000 before the result is widened to long. Bug 2: (int) bytes keeps the low 32 bits of 5,368,709,120, which happen to be exactly 1 GB, so the customer is billed for one fifth of the data. Bug 3: the cast to int truncates the cents instead of rounding. The fixed version multiplies with Math.multiplyExact and a long operand, keeps the size in a long, does the money arithmetic in BigDecimal with an explicit rounding mode, and shows that Math.toIntExact would have stopped bug 2 with an exception.
Example 3 — Reading unsigned bytes from a binary header
Problem. A binary format stores a length of 200 in one byte, 0xC8. Java's byte is signed, so the parser reads -56 and later fails with a NegativeArraySizeException.
public class UnsignedBytes {
public static void main(String[] args) {
byte[] h = {(byte) 0xC8, 0x01, (byte) 0xFF, 0x10}; // from a file
int wrongLen = h[0]; // sign-extended: -56
int len = h[0] & 0xFF; // low 8 bits only: 200
int alsoLen = Byte.toUnsignedInt(h[0]); // the same, by name
System.out.println(wrongLen + " " + len + " " + alsoLen);
int big = (h[0] & 0xFF) << 8 | (h[1] & 0xFF); // big-endian 16 bits
int broken = h[0] << 8 | h[1]; // the sign bits leak in
System.out.println(big + " vs " + broken);
int word = (h[2] & 0xFF) << 24 | (h[3] & 0xFF) << 16;
System.out.println(word + " unsigned " + Integer.toUnsignedLong(word));
}
}-56 200 200
51201 vs -14335
-15728640 unsigned 4279238656Why it behaves this way. Widening a byte to int sign-extends it: the top bit of 0xC8 is 1, so the 24 new bits are all 1 and the value is -56 (Figure 6). & 0xFF clears those bits and leaves 200, and Byte.toUnsignedInt does the same by name. When bytes are combined into a larger number, every byte needs the mask, otherwise the sign bits of one byte overwrite the others. The last line shows the same issue one level up: a 32-bit value with the top bit set is negative as an int and needs Integer.toUnsignedLong to be read as unsigned.

Example 4 — Reference casts: ClassCastException versus a pattern
Problem. Messages arrive as Object from a generic inbox. The first loop casts each one to Card; the second uses a type pattern in a switch.
import java.util.List;
public class RefCasts {
sealed interface Payment permits Card, Upi {}
record Card(String last4, long paise) implements Payment {}
record Upi(String vpa, long paise) implements Payment {}
public static void main(String[] args) {
List<Object> inbox = List.of(new Card("4242", 99_900),
new Upi("asha@upi", 500), "noise");
for (Object o : inbox) {
try {
Card c = (Card) o; // compiles; checked at run time
System.out.println("cast ok: " + c.last4());
} catch (ClassCastException e) {
String type = o.getClass().getSimpleName();
System.out.println("cast failed: " + type);
}
}
for (Object o : inbox) {
String text = switch (o) { // test and cast in one step
case Card c -> "card " + c.last4();
case Upi u -> "upi " + u.vpa();
default -> "ignored";
};
System.out.println(text);
}
Payment p = new Upi("ravi@upi", 100);
Object up = p; // upcast: implicit, no check
System.out.println(up == p); // one object, two views
}
}cast ok: 4242
cast failed: Upi
cast failed: String
card 4242
upi asha@upi
ignored
trueWhy it behaves this way. A reference cast compiles for any plausible target type and is checked only at run time, so the Upi and the String throw ClassCastException. The switch tests and casts in one step and needs a default, because the selector type is Object, not the sealed Payment. The last line shows that an upcast to Object creates no new object: the two variables are two views of the same reference.
7Common Problems & Mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Overflow before widening in time or size calculations | The product is computed in int and is already wrong before it reaches the long | Make the first operand long (24L) or use Math.*Exact (Example 2) |
| Casting long IDs or sizes to int | The low 32 bits are kept silently: wrong IDs, negative sizes | Math.toIntExact, which throws instead of corrupting |
| Casting a double amount to int to "round" | A cast truncates toward zero: 2.99 becomes 2 | Math.round, or BigDecimal.setScale with a rounding mode |
| Downcasting with an unchecked cast | ClassCastException when an unexpected type arrives | instanceof pattern, or redesign with polymorphism (Example 4) |
| Assuming (byte) of a large number is clamped | Integer narrowing wraps; (byte) 200 is -56 | Check the range first; only floating-point to integer saturates |
| Reading bytes from files or sockets as signed | Values of 128 and above become negative lengths and checksums | b & 0xFF or Byte.toUnsignedInt (Example 3) |
| Number.intValue() on a value of unknown size | It narrows like a cast, without any check | longValue() or Math.toIntExact; BigDecimal.intValueExact() |
8Performance & Production Considerations
Conversions are cheap — typically one CPU instruction or none. Their cost is in correctness: truncated IDs, negative sizes and wrong time spans are production incidents that tests with small values never catch. Test boundaries: values just below and above 2^31.
9Architecture & Design Considerations
Conversion bugs cluster at boundaries: database columns (BIGINT read into int), JSON numbers (large integers parsed as double in JavaScript clients lose precision above 2^53), protocol fields and legacy APIs. Defining types for identifiers, amounts and durations at the boundary — long IDs, BigDecimal amounts, java.time.Duration — and converting explicitly with exact methods keeps these bugs out of the core.
10Interview Questions & Answers
What is the difference between widening and narrowing conversion?
Widening converts to a type with a larger range and is automatic; it cannot lose magnitude. Narrowing converts to a smaller range, needs an explicit cast and can lose information. Widening to float or double can still lose low-order digits, as float f = 16_777_217 shows.
What is the type of byte + byte, and why?
int. Binary numeric promotion converts both operands to at least int before the addition, so assigning the result back to a byte requires a cast (or a compound assignment, which casts implicitly).
What does (byte) 300 evaluate to? And (int) 1e20?
(byte) 300 is 44, because integer narrowing keeps the low 8 bits. (int) 1e20 is Integer.MAX_VALUE, because floating-point to integer conversion saturates at the target type's range.
Why can long ms = days * 24 * 60 * 60 * 1000; give a negative number?
The whole expression is evaluated in int arithmetic because all operands are int; it overflows before the result is widened to long. Making one early operand long (24L) or using Math.multiplyExact fixes it.
What is the difference between a primitive cast and a reference cast?
A primitive cast produces a new value, possibly losing information. A reference cast produces no new object; it changes the static type used to view the same object and is checked at run time, throwing ClassCastException if the object is not of that type.
A service stored file sizes in an int and started reporting negative sizes for large uploads. What would you change?
Sizes above 2 GB overflow an int. Use long throughout — fields, database columns, API contracts — and convert with Math.toIntExact wherever an int is genuinely required so that overflow fails loudly. Add boundary tests with values above 2^31.
How do you prevent numeric conversion problems across service boundaries?
Define canonical types per concept (long or UUID for IDs, BigDecimal plus currency for money, Duration or Instant for time), document them in API contracts, serialise large integers as strings for JavaScript clients, use exact conversion methods at the edges, and include boundary values in contract tests.
Where does Java apply conversions automatically?
In assignment, when a value is stored in a variable of a wider type; in method invocation, when an argument is passed to a wider parameter type; in numeric promotion, before arithmetic on mixed types; in string concatenation, where every operand is converted to a String; and in casting contexts for boxing and unboxing (3.5). Upcasting a reference to a supertype is also automatic. Every conversion that may lose information, apart from the precision of widening to floating point, needs a cast.
Why does byte b = 10; compile without a cast, while byte b = i; does not, for an int i?
public class ConstantNarrowing {
static final int TEN = 10;
void run(int i) {
byte a = 10; // fine: constant expression that fits in byte
byte b = TEN; // fine: TEN is a compile-time constant
byte c = i; // compile error: possible lossy conversion
byte d = 200; // compile error: 200 does not fit
}
}10 is a constant expression, and the JLS allows an assignment to narrow a constant of type int to byte, short or char when the value fits; javac checks the value at compile time. A variable could hold any int, so byte c = i is rejected with "possible lossy conversion from int to byte", and so is the constant 200, which does not fit. A static final int initialised with a constant counts as a constant too.
What does this program print?
public class CastQuiz {
public static void main(String[] args) {
System.out.println((int) (char) -1);
System.out.println((short) 40_000);
System.out.println((long) 1e19 == Long.MAX_VALUE);
System.out.println((int) -2.7 + " " + Math.round(-2.5));
System.out.println(Math.round(2.5));
}
}It prints 65535, -25536, true, -2 -2, 3. (char) -1 keeps the low 16 bits, all ones, and char is unsigned, so it is 65535. 40,000 does not fit in a short, so the low 16 bits are read as -25,536. (long) 1e19 saturates at Long.MAX_VALUE. (int) -2.7 truncates toward zero, while Math.round adds 0.5 and takes the floor, so -2.5 rounds to -2 and 2.5 to 3, which is not the "half away from zero" rule many people expect.
What does the JVM do for (int) someDouble and for (Card) someObject?
The first compiles to d2i, which truncates toward zero, returns 0 for NaN and saturates at Integer.MIN_VALUE or MAX_VALUE, exactly as the JVM specification defines, so the result is the same on every CPU even though the hardware instruction behaves differently. The second compiles to checkcast: no new object is created, the JVM checks the object's class against Card and throws ClassCastException on a mismatch, and the JIT removes the check where it can prove the type. Both are cheap; their cost is in correctness, not speed.
A public API returns 64-bit IDs and its main clients are browsers. Number or string in the JSON?
JavaScript numbers are IEEE 754 doubles, exact only up to 2^53 - 1, so IDs above that, for example from Snowflake-style generators, arrive rounded and may point to another record. Strings are always exact and make clear that the ID is opaque, at the cost of a slightly larger payload and a conversion on the server; numbers are natural and fine while IDs stay small, but that is hard to guarantee for the life of an API. Most public APIs therefore use strings for IDs from the start, and document it in the schema, since changing the type later is a breaking change.
An order ID column must move from INT to BIGINT because it will pass 2^31 within a year. Several services and a reporting tool read it. How do you plan the change?
First find every consumer and every place the value is typed as int: Java fields and DTOs, JDBC mappings, message schemas, caches, the reporting tool and any client SDKs. Change the code to long and deploy that everywhere while the values are still small, so that both types work. Then migrate the column, online if the database supports it or through a new column with backfill and a switch, and add monitoring for values approaching the old limit as an early warning. Add tests with IDs above 2^31 to every service, so that a future (int) cast is caught.
How would you prevent unit and conversion errors in a platform that handles money, durations and data sizes?
Do not pass these values as bare numbers. Use types that carry the unit: Duration and Instant for time, a Money value type with an amount and a currency, and a small DataSize type for bytes, so that converting between units is a method call with a defined rule instead of a multiplication someone can get wrong. At the boundaries, map external formats to these types once, with exact conversions that throw. Where bare numbers remain, put the unit in the name (timeoutMs, sizeBytes) and enforce it with review rules and API linting.
Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Widening is automatic and safe for magnitude; narrowing needs a cast and can lose data.
- Integer narrowing discards high bits; floating-point to integer truncates and saturates.
- byte, short and char are promoted to int in arithmetic.
- Overflow can happen before widening: make the first operand long.
- Use Math.toIntExact, addExact and multiplyExact where silent loss is unacceptable.