Java Arithmetic, Numeric Promotion, Casting and Assignment Operators (OCP 21)
The OCP Java 21 rules for arithmetic: integer division and modulus, division by zero, the four numeric promotion rules, widening and narrowing casts, overflow, constant expressions, compound assignment's hidden cast and the value of an assignment.
kvi5hnuCode Sprout team member9 min readOn this page
Most "does this compile?" questions on the exam are about types: what an arithmetic expression produces, and whether that type fits the variable on the left side of =. This article covers the binary arithmetic operators, the promotion rules that set their result type, casting, and the assignment operators, including the compound forms that cast for you.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | addition (also String concatenation) | 7 + 2 | 9 |
- | subtraction | 7 - 2 | 5 |
* | multiplication | 7 * 2 | 14 |
/ | division | 7 / 2 | 3 |
% | remainder (modulus) | 7 % 2 | 1 |
They work on every numeric primitive type (char counts as numeric), never on boolean. Of these, only + (and +=) works on String values, where it concatenates. That's covered in the core APIs chapter. *, / and % have higher precedence than + and - (article 8).
Integer division and remainder
When both operands are integers, / discards the fraction. It truncates toward zero, so 7 / 2 is 3 and -7 / 2 is −3. % gives the remainder that goes with that division:
System.out.println(9 / 3 + " " + 9 % 3); // 3 0
System.out.println(10 / 3 + " " + 10 % 3); // 3 1
System.out.println(11 / 3 + " " + 11 % 3); // 3 2
System.out.println(12 / 3 + " " + 12 % 3); // 4 0
For a positive divisor n and a non-negative left operand, x % n cycles through 0 to n − 1. With negative numbers, the result takes the sign of the left operand. The sign of the divisor doesn't matter:
| Expression | Result |
|---|---|
7 % 5 | 2 |
7 % -5 | 2 |
-7 % 5 | -2 |
-7 % -5 | -2 |
If you need a remainder that's never negative, as in clock or array-index arithmetic, use Math.floorMod(-7, 5), which returns 3. Math.floorDiv is the matching division that rounds down.
% also works on floating-point values (7.5 % 2 is 1.5), but the exam focuses on integers.
Division by zero
- Integer division or remainder by zero throws
ArithmeticException: / by zeroat runtime. The compiler doesn't reject it, thoughjavac -Xlintwarns when the zero is a literal. - Floating-point division never throws:
1.0 / 0isInfinity,-1.0 / 0is-Infinity, and0.0 / 0isNaN(not a number).
Numeric promotion
Before a binary arithmetic operator runs, Java converts both operands to a common type. Four rules decide it:
- If the operands have different types, the smaller type is promoted to the larger one.
- If one is an integer type and the other is floating-point, the integer is promoted to the floating-point type.
byte,shortandcharare always promoted tointfirst, even when both operands share that type.++and--are the exception (article 8).- The result has the promoted type.

Applying the rules:
| Expression | Promoted to | Result type |
|---|---|---|
int * long | long | long |
long + float | float | float |
short * short | int | int |
byte + char | int | int |
short * float / double | int, then float, then double | double |
char + 1 | int | int |
A trap from the literal rules comes up here too: float y = 2.1; doesn't compile, because 2.1 is a double. That has nothing to do with promotion.
Promotion happens step by step, in evaluation order. In 1 / 2 * 4.0, the integer division 1 / 2 runs first and gives 0, and only then is the result promoted, so the answer is 0.0. 4.0 * 1 / 2 is 2.0, because the double comes first.
Assigning values and casting
The simple assignment operator = stores the right-hand value in the variable on the left. It compiles automatically when the value widens, that is, when it goes in the direction of the arrows above:
long big = 123; // int widens to long
double d = 7; // int widens to double
float f = 10L; // long widens to float
Going the other way is narrowing, and the compiler refuses unless you cast:
int fish = 1.0; // DOES NOT COMPILE: double to int
int mammal = 9f; // DOES NOT COMPILE: float to int
float egg = 2.0 / 9; // DOES NOT COMPILE: double to float
short frog = 3 - 2.0; // DOES NOT COMPILE: double to short
A cast writes the target type in parentheses in front of a value:
int fish = (int) 1.0; // 1
int whole = (int) 9.99; // 9: the fraction is dropped, not rounded
short tail = (short) (4 + 10); // parentheses: cast the whole sum
long bad = 10 (long); // DOES NOT COMPILE: the type goes first
A cast is a unary operator with high precedence, so it applies only to the operand directly after it:
short a = 10, b = 3;
short c = a * b; // DOES NOT COMPILE: short * short is an int
short d = (short) a * b; // DOES NOT COMPILE: only a is cast; the product is still an int
short e = (short) (a * b); // OK
short g = 1 + (short) (a * b); // DOES NOT COMPILE: 1 + short is an int again
Casts between boolean and numbers never compile, and neither do casts between String and numbers: (int) "5" is an error. Use Integer.parseInt instead.
Overflow and lossy casts
Narrowing keeps only the low-order bits that fit, and integer arithmetic wraps around when it overflows. Neither throws an exception:
short s = (short) 1_921_222; // 20678
byte b = (byte) 200; // -56 (200 - 256)
int max = Integer.MAX_VALUE;
int next = max + 1; // -2147483648: wrapped
The most dangerous overflow happens before a widening assignment:
long wrong = 1_000_000 * 3_000; // -1294967296: int * int overflows first
long right = 1_000_000L * 3_000; // 3000000000: one long operand is enough
Math.addExact, Math.subtractExact, Math.multiplyExact and Math.toIntExact throw ArithmeticException on overflow instead of wrapping. Use them when a wrong number is worse than an exception.
Floating-point to integer casts drop the fraction, and values out of range become the nearest limit: (int) 1e20 is Integer.MAX_VALUE, and (int) Double.NaN is 0.
Constant values versus variables
The narrowing rule has one important exception. If the right side is a constant expression of type int, short, char or byte, and its value fits, it can be assigned to a byte, short or char without a cast:
byte hat = 1;
byte gloves = 7 * 10; // OK: the constant 70 fits in a byte
short boots = 2 + 1; // OK
char letter = 65 + 1; // OK: 'B'
short socks = 2 + hat; // DOES NOT COMPILE: hat is a variable, so the sum is just an int
byte mittens = 7 * 100; // DOES NOT COMPILE: 700 doesn't fit in a byte
A final local variable initialized with a constant is a constant variable, so the exception applies to it too: final byte hat = 1; short boots = 2 + hat; compiles. The exception never applies to long constants (final long k = 10; int i = k; fails) or to floating-point types.
Compound assignment operators
The compound operators combine an operation with assignment:
| Operator | Equivalent to |
|---|---|
a += b | a = (type of a) (a + b) |
a -= b | a = (type of a) (a - b) |
a *= b | a = (type of a) (a * b) |
a /= b | a = (type of a) (a / b) |
a %= b | a = (type of a) (a % b) |
Others exist for the bitwise and shift operators (&=, |=, ^=, <<=, >>=, >>>=).
Note the hidden cast to the type of the left-hand variable. It makes some lines compile that would fail written out longhand:
int sheep = 5;
long goat = 10;
sheep = sheep * goat; // DOES NOT COMPILE: long to int
sheep *= goat; // OK: computed as long, then cast to int
byte level = 120;
level += 10; // OK, and level wraps to -126
int i = 7;
i /= 2.0; // OK: 3.5 cast to int gives 3
The left side must be an existing, initialized variable. x *= 2; with no declared x, or with an uninitialized local x, doesn't compile.
The value of an assignment
An assignment is an expression, and its value is the value that was assigned. That allows chaining and assignments inside larger expressions:
int a, c;
a = c = 7; // right to left: c = 7, then a = 7
long wolf = 5;
long coyote = (wolf = 3) + 1; // wolf is 3, coyote is 4
The exam uses this most often with boolean:
boolean healthy = false;
if (healthy = true) { // assigns true, and the expression's value is true
System.out.print("Good!"); // always prints
}
= assigns and == compares. With an int the mistake doesn't compile (if (x = 5) gives an int, not a boolean), but with a boolean variable it compiles silently.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Since Java 17 all floating-point arithmetic is strict (JEP 306), so results are the same on every platform and
strictfpdoes nothing. - Java 25 added
Math.powExactandMath.unsignedMultiplyExact, which throwArithmeticExceptionon overflow instead of wrapping like*does. They aren't on either exam (article 22).
Exam traps from this article
A complete example
public class Solution {
@SuppressWarnings("lossy-conversions") // section 5 narrows on purpose
public static void main(String[] args) {
// 1. Integer division drops the fraction; % is the remainder and takes the sign of the left operand.
System.out.println("17 / 5 = " + 17 / 5 + ", 17 % 5 = " + 17 % 5);
System.out.println("-17 / 5 = " + -17 / 5 + ", -17 % 5 = " + -17 % 5
+ ", Math.floorMod(-17, 5) = " + Math.floorMod(-17, 5));
// 2. Promotion: the result type comes from the promoted operands.
short w = 14;
float x = 13;
double y = 30;
var mixed = w * x / y; // short -> int -> float -> double
byte b1 = 10, b2 = 20;
int sum = b1 + b2; // byte + byte is an int
System.out.println("w * x / y = " + mixed + ", b1 + b2 = " + sum);
// 3. Casting narrows explicitly, and may truncate or wrap.
double price = 9.99;
int whole = (int) price; // fraction dropped, not rounded
short wrapped = (short) 1_921_222; // keeps only the low 16 bits
byte tiny = (byte) 200; // 200 - 256
System.out.println(whole + " " + wrapped + " " + tiny + " " + Math.round(price));
// 4. Overflow is silent with int arithmetic, even when the target is a long.
long wrong = 1_000_000 * 3_000; // int * int overflows before widening
long right = 1_000_000L * 3_000; // a long operand makes it long arithmetic
System.out.println(wrong + " vs " + right);
try {
Math.multiplyExact(1_000_000, 3_000);
} catch (ArithmeticException e) {
System.out.println("multiplyExact: " + e.getMessage());
}
// 5. Compound assignment casts back to the variable's type automatically.
int sheep = 5;
long goat = 10;
sheep *= goat; // like sheep = (int) (sheep * goat)
byte level = 120;
level += 10; // like level = (byte) (level + 10): wraps
System.out.println("sheep=" + sheep + ", level=" + level);
// 6. An assignment is an expression whose value is the value assigned.
int a, c;
a = c = 7;
long wolf = 5;
long coyote = (wolf = 3) + 1;
System.out.println(a + c + " " + wolf + " " + coyote);
// 7. Division by zero: integers throw, floating point gives Infinity or NaN.
System.out.println(1.0 / 0 + " " + 0.0 / 0);
int zero = 0;
try {
System.out.println(10 / zero);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " + e.getMessage());
}
}
}
Output:
17 / 5 = 3, 17 % 5 = 2
-17 / 5 = -3, -17 % 5 = -2, Math.floorMod(-17, 5) = 3
w * x / y = 6.066666666666666, b1 + b2 = 30
9 20678 -56 10
-1294967296 vs 3000000000
multiplyExact: integer overflow
sheep=50, level=-126
14 3 4
Infinity NaN
ArithmeticException: / by zero
Points to notice:
-17 % 5is −2, butMath.floorMod(-17, 5)is 3.Math.round(9.99)returns 10 (along), while the cast(int) 9.99truncates to 9.- The two "3 billion" lines differ only in an
L, and one of them is silently wrong. a + c + " "adds first (7 + 7 = 14) because the leftmost+has twointoperands.
Common questions
Why does Java promote byte and short to int at all?
The JVM's arithmetic instructions work on int, long, float and double. There are no byte-sized add instructions. The language makes that visible by giving byte + byte the type int.
Is x += y exactly the same as x = x + y?
Almost. The compound form includes a cast to x's type, and it evaluates x only once. That matters for expressions with side effects, such as arr[i++] += 2.
Does a cast round or truncate?
Casting a floating-point value to an integer type truncates toward zero. Math.round rounds to the nearest whole number, with halves rounding up: Math.round(2.5) is 3 and Math.round(-2.5) is −2.
Why does 0.1 + 0.2 print 0.30000000000000004?
double stores binary fractions, which can't represent 0.1 exactly. Use BigDecimal for money. The exam won't ask you to predict these digits.
Can I cast between char and short?
Yes, with an explicit cast in either direction. Both are 16 bits, but short is signed and char isn't, so neither widens automatically to the other.
Summary
/on integers truncates toward zero.%gives the remainder with the sign of the left operand. Integer division by zero throws, floating-point division by zero givesInfinityorNaN.- Promotion: smaller to larger, integer to floating-point,
byte/short/charalways toint. The result has the promoted type. - Widening assignments are automatic. Narrowing needs a cast, which truncates or wraps silently.
- A cast applies only to the operand right after it. Parenthesize the whole expression to cast it.
- An
intconstant that fits can be assigned tobyte,shortorcharwithout a cast. A variable, or alongconstant, can't. - Compound assignments include a hidden cast to the left side's type.
- An assignment is an expression with the assigned value.
if (b = true)assigns.
Practice quiz
Test yourself with the arithmetic, promotion and casting quiz: 10 exam-style questions with explanations.
Previous: Java Operators: Types, Precedence and Unary Operators (OCP 21)
Next: Java Equality, Relational, Logical and Ternary Operators (OCP 21)
Related reading
- Java Operators: Types, Precedence and Unary Operators (OCP 21)
- Java Variable Scope and Garbage Collection (OCP 21)
- Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Creating Objects in Java: Constructors, Instance Initializers and Order of Initialization (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.