Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 201 ยท Operators

Arithmetic Operators

Learn Java's arithmetic operators, unary minus, string concatenation with +, integer vs floating-point division, operator precedence and the numeric promotion rules behind every result.

An operator is a symbol that combines values into a new value. price * quantity uses the multiplication operator, and "Hi, " + name uses + to join text. Java's arithmetic operators are the ones you know from math class, +, -, *, / and %, plus unary + and - that work on a single value.

They look simple, and for everyday numbers they are. But the type of each operand decides what an operator really does: 7 / 2 is 3 while 7.0 / 2 is 3.5, 1 + 2 + "3" is "33" while "1" + 2 + 3 is "123", and adding two byte values gives an int. This lesson explains every arithmetic operator, the precedence rules for combining them, and the numeric promotion rules that determine the type of every result.

The five binary operators

A binary operator takes two operands, one on each side:

Operator Name Example Result
+ addition (or string concatenation) 7 + 2 9
- subtraction 7 - 2 5
* multiplication 7 * 2 14
/ division 7 / 2 3 (integer division)
% remainder 7 % 2 1
Java Arithmetic on ints and doubles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the parentheses inside each println. Without them, "a + b = " + a + b would join the text with 17 and then with 5, printing a + b = 175. That's string concatenation at work, explained below.

Division and remainder, briefly

Working with Numbers covers division in depth, so here are just the rules to keep in mind:

  • When both operands are integers, / is integer division: it truncates toward zero (-7 / 2 is -3).
  • When either operand is float or double, / is ordinary division (7 / 2.0 is 3.5).
  • % returns the remainder, with the sign of the left operand (-7 % 2 is -1).
  • Integer division or remainder by zero throws ArithmeticException; floating-point division by zero gives Infinity or NaN.

Unary plus and minus

The unary operators take a single operand:

  • -x negates a value: -5, -price, -(a + b).
  • +x returns the value unchanged. It exists for symmetry and is almost never needed, though it does trigger promotion (below).
Java
int balance = 120;
int debt = -balance;        // -120
int back = -debt;           // 120
int same = - -5;            // 5 (the space keeps it from being --, the decrement operator)

Negation can overflow at one point: -Integer.MIN_VALUE is still Integer.MIN_VALUE, because +2,147,483,648 doesn't fit in an int. Math.negateExact throws instead, if you need the check.

The increment and decrement operators ++ and -- are also unary, but because they change a variable they belong with assignment, in Assignment and Increment Operators.

Precedence and associativity

When an expression has several operators, precedence decides which run first, just like in math:

  1. Unary +, - (and casts) bind tightest.
  2. Then *, /, %, which share one level.
  3. Then + and -, which share the next level.

Operators on the same level are evaluated left to right (they're left-associative). That matters for - and /, which aren't symmetric:

Java
2 + 3 * 4        // 14: multiplication first
(2 + 3) * 4      // 20: parentheses first
10 - 4 - 3       // 3: (10 - 4) - 3, not 10 - (4 - 3)
100 / 10 / 5     // 2: (100 / 10) / 5
7 % 3 * 2        // 2: (7 % 3) * 2, same level, left to right
-2 * 3           // -6: unary minus first

When in doubt, add parentheses. They cost nothing at run time and save the next reader from having to remember the table. The full precedence table, including comparison and logical operators, is in Operator Precedence and the Ternary Operator.

Order matters with integer division

Left-to-right evaluation combines with integer division to create one of the classic bugs. Converting 25 ยฐC to Fahrenheit:

Java Same formula, different order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

9 / 5 * celsius computes 9 / 5 first, which is 1, so the result is just celsius + 32. In math these formulas are equal; in integer arithmetic they're not. Either multiply before dividing or, better, make one operand a double (9.0) so the whole calculation uses floating point.

String concatenation with +

+ has a second job: when at least one operand is a String, it concatenates, converting the other operand to text. Every type can be converted: numbers, char, boolean, null (which becomes "null") and any object (through its toString() method).

The trap is left-to-right evaluation. Each + looks only at its own two operands, so whether a + adds or concatenates depends on what has happened so far:

Java When + adds and when it joins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Rules of thumb:

  • Put arithmetic in parentheses whenever it appears in a concatenation: "Total: " + (a + b).
  • *, / and % have higher precedence than +, so "Area: " + w * h works without parentheses. Only + and - cause trouble ("x" + a - b doesn't even compile, because you can't subtract from a String).
  • char values are numbers in arithmetic ('A' + 1 is 66) and characters in concatenation. Characters and Booleans has the details.

For building strings in loops or from many pieces, + creates a lot of temporary objects; use StringBuilder or String.join instead. For readable output with numbers, String.format and printf usually beat long + chains (see Formatting Strings).

Numeric promotion: what type is the result?

Java's CPU-level arithmetic works on four types only: int, long, float and double. Before any arithmetic operator runs, Java promotes the operands to a common type. These rules are called binary numeric promotion, and they apply to +, -, *, / and % (and to comparisons):

  1. If either operand is a double, the other is converted to double.
  2. Otherwise, if either is a float, the other becomes float.
  3. Otherwise, if either is a long, the other becomes long.
  4. Otherwise, both become int, even if they were byte, short or char.

The result has that common type. A few consequences:

Expression Operand types Result type
5 / 2 int, int int (2)
5 / 2.0 int, double double (2.5)
3L * 4 long, int long
1.5f + 2 float, int float
1.5f + 2.0 float, double double
byteA + byteB byte, byte int
'a' + 'b' char, char int (195)

Unary + and - promote too: -b for a byte b is an int. That's why this fails:

Java
byte a = 10, b = 20;
byte sum = a + b;            // error: incompatible types: possible lossy conversion from int to byte
byte neg = -a;               // same error
byte fixed = (byte) (a + b); // OK with an explicit cast
Java Seeing promotion in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The overloaded typeOf methods reveal the static type of each expression, as in Local Variable Type Inference with var.

Two lessons stand out in the last part:

  • Promotion happens one operator at a time. In 5 / 2 * 2.0, the division sees two int values and runs integer division before the double ever appears.
  • Promotion is not protection. Two int values stay int, so a + b overflows to a negative number before the division, and the "average" of two positive numbers is -147483648. This exact bug once lived in the JDK's own binary search for years. Compute a + (b - a) / 2, or widen one operand to long first.

Assigning a result to a wider variable doesn't change how it's computed. In long total = count * price; with two int operands, the multiplication still runs in int and can overflow before the value reaches total. Widen an operand: (long) count * price.

Evaluation order

Java guarantees that the operands of a binary operator are evaluated left to right: the left operand is fully evaluated before the right one. This only matters when evaluating an operand has a side effect, such as a method call that prints something or an increment:

Java
int i = 1;
int result = i + i++ * 10;   // 11: left i is read as 1, then i++ gives 1 (i becomes 2)

Code like that is legal but hard to read, and in a code review it would rightly be rejected. Keep side effects (++, --, assignments, method calls that change state) out of larger expressions. Assignment and Increment Operators has more puzzles of this kind, and why to avoid them in real code.

Putting it together

Here's a small receipt calculator that uses everything from this lesson: integer math for whole cents, / and % to split a total, floating point only where it makes sense, and parentheses inside concatenation:

Java A receipt in whole cents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The Input box holds two items (3 at 12.99 and 2 at 4.50). Try your own values. Storing money as whole cents keeps every addition exact; the only floating-point step is the tax, which is rounded straight back to a whole cent with Math.round. / 100 and % 100 then split cents into dollars and cents, and %02d pads the cents to two digits.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does IO.println("Total: " + 4 + 6); print?

    • is evaluated left to right. "Total: " + 4 is already a String, so + 6 concatenates again. Write "Total: " + (4 + 6) to add first.
  2. 2. What is the value of 20 - 10 / 5 * 2?

    / and * have higher precedence than - and are evaluated left to right: 10 / 5 = 2, then 2 * 2 = 4, and finally 20 - 4 = 16.
  3. 3. Given byte a = 5, b = 6;, what is the type of a + b?

    Binary numeric promotion converts byte, short and char operands to int before arithmetic, so the result is an int. Storing it in a byte needs a cast.
  4. 4. What does IO.println(7 / 2 * 2.0); print?

    Evaluation goes left to right: 7 / 2 is integer division, giving 3. Only then is 3 promoted to double for 3 * 2.0 = 6.0.
  5. 5. Why can (a + b) / 2 give a negative result for two large positive ints?

    Both operands are int, so the sum is computed in int and wraps around when it exceeds Integer.MAX_VALUE. Use a + (b - a) / 2 or widen to long first.

Summary

  • Java's arithmetic operators are +, -, *, /, % and unary +/-.
  • / on two integers truncates toward zero; % keeps the sign of the left operand; integer division by zero throws.
  • *, /, % bind tighter than +, -; operators on one level run left to right. Order matters with integer division: multiply first or use double.
  • + concatenates when either operand is a String, evaluated left to right, so wrap arithmetic in parentheses inside concatenations.
  • Numeric promotion: double beats float beats long, otherwise everything becomes int, including byte, short and char. Unary minus promotes too.
  • Promotion happens per operator and doesn't prevent int overflow; widen an operand ((long) a * b) before the risky operation.
  • Operands are evaluated left to right; keep side effects out of bigger expressions.

Next: Assignment and Increment Operators, where you'll learn compound assignment, its hidden cast, and the difference between ++x and x++.