Java Type Conversion and Casting: Widening, Narrowing and Compound Assignment
When Java converts numbers automatically and when you need a cast. Covers widening conversions and precision loss, the rules for mixed-type expressions, casts and how they truncate, out-of-range casts, compound assignment's hidden cast, and assignment as an expression.
kvi5hnuCode Sprout team member10 min readOn this page
Programs constantly mix numeric types: an int count multiplied by a double price, a long timestamp divided by an int. Java has precise rules for when values are converted automatically and when you must request a conversion with a cast. Knowing them explains many compiler errors, and a few silent surprises.
Automatic (Widening) Conversions
Java automatically converts a value to a "wider" type when no information can be lost, or at least not the magnitude. The legal automatic conversions are:

- Solid arrows are exact:
byte → short → int → long,char → int,int → double,float → double. (Following arrows transitively is also allowed:byteconverts todouble, for instance.) - Dashed arrows (
int → float,long → float,long → double) keep the magnitude but may lose precision: the low-order digits.
int n = 123_456_789;
float f = n; // allowed automatically, but f is 1.23456792E8
A float has only about 7 significant digits, so 123456789 becomes 123456792. Similarly, a long has up to 19 digits, while a double keeps only about 15–17, so very large long values can't be represented exactly as double:
public class Solution {
public static void main(String[] args) {
int n = 123_456_789;
float f = n; // automatic, but loses precision
double d = n; // automatic and exact
System.out.println(f + " " + d);
long big = 9_007_199_254_740_993L;
double approx = big; // long -> double can lose digits
System.out.println(big + " -> " + (long) approx);
double x = 9.997;
int truncated = (int) x; // cast drops the fraction
int rounded = (int) Math.round(x); // round first
System.out.println(truncated + " " + rounded);
System.out.println((int) -9.997);
System.out.println((byte) 300 + " " + (short) 70_000 + " " + (int) 3e10);
System.out.println((int) Double.NaN + " " + (char) 65 + " " + (int) 'z');
System.out.println(5 / 2 * 2.0 + " " + 5 / 2.0 * 2);
}
}
1.2345679E8 1.23456789E8
9007199254740993 -> 9007199254740992
9 10
-9
44 4464 2147483647
0 A 122
4.0 5.0
(2⁵³ + 1 = 9,007,199,254,740,993 is the smallest positive integer a double can't represent exactly.)
Conversions in the other direction (double → int, long → int, int → byte, and so on) can lose information, so Java never does them silently. The compiler reports an error instead:
long n = 5;
int k = n; // error: incompatible types: possible lossy conversion from long to int
float f = 1.5; // error: possible lossy conversion from double to float
Mixed Types in an Expression
When a binary operator such as +, * or < combines two values of different types, both are converted to a common type before the operation. The rule is a simple ladder, checked from the top:
- If either operand is
double, the other is converted todouble. - Otherwise, if either is
float, the other is converted tofloat. - Otherwise, if either is
long, the other is converted tolong. - Otherwise, both are converted to
int.
Rule 4 has an important consequence: arithmetic on byte, short and char always produces an int, even when both operands are the small type:
byte b = 10;
b = b + 5; // error: possible lossy conversion from int to byte
b + 5 is an int, and an int can't be stored in a byte without a cast. (Compound assignment b += 5 works; see below.)
Conversions happen per operation, left to right, which matters in longer expressions. The last line of the example shows this:
5 / 2 * 2.0: first5 / 2is integer division =2, then2 * 2.0=4.0.5 / 2.0 * 2: first5 / 2.0=2.5(one operand isdouble), then2.5 * 2=5.0.
The "double" in the expression arrives too late in the first version to rescue the division.
Casts: Explicit Conversions
When you want a conversion that might lose information, you use a cast: the target type in parentheses before the value.
double x = 9.997;
int nx = (int) x; // 9: the fractional part is discarded
Casting a floating-point number to an integer
A cast from double (or float) to an integer type truncates toward zero: it simply drops the fraction. (int) 9.997 is 9, and (int) -9.997 is -9. It does not round.
To round to the nearest integer, call Math.round first, and cast its result:
int nx = (int) Math.round(x); // 10
You still need the (int) because Math.round(double) returns a long, and converting long to int could lose information.
Special cases when casting floating-point values to integers:
| Value | (int) result |
|---|---|
Too large (e.g. 3e10) | Integer.MAX_VALUE (2147483647) |
Too small (e.g. -3e10) | Integer.MIN_VALUE |
NaN | 0 |
Casting between integer types: bits are cut off
Casting to a smaller integer type keeps only the lowest bits that fit. The result can be a completely different number:
(byte) 300→44. 300 is1_0010_1100in binary; abytekeeps the lowest 8 bits,0010_1100= 44.(short) 70_000→4464(70,000 − 65,536).(byte) 200→-56, because the bit pattern1100_1000is negative in a signed byte.
No error is reported. If an out-of-range value would be a bug, use Math.toIntExact(longValue), which throws an exception instead.
Casts with char
char converts automatically to int (giving its code), and an int can be cast to char:
int code = 'z'; // 122
char c = (char) 65; // 'A'
char next = (char) ('a' + 1); // 'b'
No casts to or from boolean
You can't cast between boolean and any numeric type. (int) true and (boolean) 1 are compile errors. If you need it, write it out:
int flagAsNumber = done ? 1 : 0;
boolean nonZero = count != 0;
This rule prevents the C/C++ habit of treating numbers as truth values, along with the bugs that come with it.
Assignment and Compound Assignment
Plain assignment
x = expression evaluates the right side and stores the result in x. The right side must be assignable to x's type: the same type, a widening conversion, or a constant that fits, as described above.
Compound assignment operators
Java has shortcuts that combine an operator with assignment:
| Shortcut | Means |
|---|---|
x += 4 | x = x + 4 |
x -= 4 | x = x - 4 |
x *= 4 | x = x * 4 |
x /= 4 | x = x / 4 |
x %= 4 | x = x % 4 |
x &= m, x |= m, x ^= m | bitwise and/or/xor with assignment |
x <<= n, x >>= n, x >>>= n | shifts with assignment |
The hidden cast in compound assignment
There's one important difference between x = x + y and x += y: compound assignment includes an automatic cast back to the type of the left side.
public class Solution {
@SuppressWarnings("lossy-conversions") // deliberate demo; remove this line to see the -Xlint warning shown below
public static void main(String[] args) {
int x = 10;
x += 4; // x = x + 4
x -= 2; // 12
x *= 3; // 36
x /= 5; // 7 (integer division)
x %= 4; // 3
System.out.println(x);
x += 3.5; // compiles! means x = (int) (x + 3.5)
System.out.println(x);
byte b = 10;
b += 5; // fine, implicit cast back to byte
// b = b + 5; // would not compile: b + 5 is an int
System.out.println(b);
int a = 1;
int c = a += 4; // assignment is an expression
System.out.println(a + " " + c);
}
}
3
6
15
5 5
b += 5is convenient: it meansb = (byte) (b + 5).x += 3.5with anintxalso compiles, silently meaningx = (int) (x + 3.5). Starting from 3, that's(int) 6.5=6: half of what you added disappeared with no warning by default.
Since Java 20, the compiler can warn about this. Compile with -Xlint (or -Xlint:lossy-conversions):
warning: [lossy-conversions] implicit cast from double to int in compound assignment is possibly lossy
x += 3.5;
^
Turning on -Xlint warnings in your build or IDE is a good habit in general.
Assignment is an expression
In Java, an assignment is an expression with a value: the value that was assigned. That's why int c = a += 4; works: a += 4 stores 5 in a, and its value, 5, is then stored in c.
The assignment operators are right-associative, so chains are evaluated from right to left:
a = b = c = 0; // means a = (b = (c = 0)); all three become 0
a += b += c; // means a += (b += c)
Chained = 0 to reset several variables is a common idiom. Beyond that, nested assignments make code hard to read. Most programmers prefer separate statements:
int a = 1;
a += 4;
int c = a;
Common questions
What does (int) Double.NaN or (int) 1e20 give?
(int) Double.NaN is 0. Values that are too large saturate at Integer.MAX_VALUE (2147483647), and values that are too small saturate at Integer.MIN_VALUE. Unlike integer-to-integer casts, floating-point casts never wrap around. They still lose information silently, so check the range first when it matters.
Why does long to float count as a widening conversion when it loses digits?
Because the range of float (up to about 3.4 × 10³⁸) is far larger than the range of long. Java guarantees you never get a wildly wrong magnitude, only lost low-order digits. The -Xlint lossy-conversion warning doesn't cover these widening cases, so be careful with large long IDs stored in float or double.
Why does 1 / 3 * 3 give 0?
1 / 3 is integer division and gives 0, and 0 * 3 is 0. Conversions happen operation by operation, left to right. Write 1.0 / 3 * 3, or reorder to 1 * 3 / 3, depending on what you mean.
How do I convert a String to a number, and back?
Use Integer.parseInt("42"), Long.parseLong, Double.parseDouble and so on. They throw NumberFormatException for bad input. Going the other way, use String.valueOf(n), Integer.toString(n), or concatenate "" + n. Casts never work between strings and numbers.
Is there a modern way to check whether a value fits before casting?
For now, use Math.toIntExact(long), which throws when the value doesn't fit, or compare against Byte.MIN_VALUE and Byte.MAX_VALUE yourself. Primitive patterns, a preview feature since Java 23 (still in preview in Java 25, 26 and 27; see article 52), will let you write if (n instanceof byte b) to test and convert in one step.
Summary
| Situation | What happens |
|---|---|
Widening (int → long, int → double, char → int, …) | Automatic and exact |
int/long → float, long → double | Automatic, may lose low-order digits |
Narrowing (double → int, long → int, int → byte, …) | Requires a cast |
| Mixed-type operation | Both operands converted to double > float > long > int |
byte/short/char arithmetic | Result is int |
(int) 9.99 | Truncates toward zero → 9; use Math.round to round |
| Out-of-range integer cast | Keeps the low bits: (byte) 300 = 44 |
| Out-of-range floating → int cast | Clamps to MIN_VALUE/MAX_VALUE; NaN → 0 |
boolean ↔ number | Never allowed; use b ? 1 : 0 |
x op= y | Includes a hidden cast to x's type; -Xlint warns |
a = b = 0 | Assignments are right-associative expressions |
Practice Questions
Which of these compile? (a) long l = 42; (b) int i = 42L; (c) double d = 'A'; (d) float f = 2.5; (e) char c = 66;
(a) yes, int widens to long; (b) no, long to int needs a cast; (c) yes, char widens to double (65.0); (d) no, 2.5 is a double, so write 2.5F; (e) yes, 66 is an int constant that fits in a char (it becomes 'B').
What do (int) 7.9, (int) -7.9, (int) Math.round(7.5) and (int) Math.round(-7.5) give?
7, -7 (casts truncate toward zero), 8 and -7 (Math.round rounds halves toward positive infinity).
short s = 1; s = s * 2; doesn't compile, but s *= 2; does. Why?
s * 2 is computed as int (all short arithmetic is promoted to int), and storing an int in a short needs a cast. Compound assignment includes that cast implicitly: s *= 2 means s = (short) (s * 2).
What is the value of (byte) 129, and why?
-127. 129 is 1000_0001 in its lowest 8 bits. As a signed byte, a leading 1 bit means negative: 129 − 256 = −127.
Evaluate 1 / 2 + 1.0 / 2 + 1 / 2.0.
0 + 0.5 + 0.5 = 1.0. The first term is integer division (0); the other two have a double operand, so they produce 0.5.
Why might int total = 0; total += price * 1.18; be a hidden bug?
price * 1.18 is a double, and += silently casts the sum back to int, dropping the fractional part every time. Totals end up too small. Declare total as double (or better, use BigDecimal for money), and compile with -Xlint to get a lossy-conversion warning.
Previous: Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More
Next: Java Operators: Increment, Relational, Logical, Conditional, Bitwise and Precedence
Related reading
- Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations
- JShell Tutorial: Java's Interactive REPL for Quick Experiments
- Using a Java IDE: IntelliJ IDEA, VS Code and Eclipse for Beginners
- How to Compile and Run Java Programs from the Command Line
- How to Install the Java JDK on Windows, macOS and Linux

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.