Explain it simply
Explain it simply
An operator is a small symbol that does one job on values. + adds, < compares, and && combines two conditions. They work like the buttons on a calculator: you put values in, press a button, and one result comes out.
The twist is that Java also cares about the type of the result. On a calculator 7 / 2 gives 3.5, but in Java two ints divide to 3. This lesson covers what each button does and why those surprising results appear.
Problem → Why → Solution
The problem: the average mark is wrong
Say you want the average of a student's two marks and write the code below. With 85 and 90 the answer should be 87.5, but the program prints 87.0. The second line prints "Total: 8590" instead of 175. There is no compile error and no crash, so the bug can slip straight into a report without anyone noticing.
public class Main {
public static void main(String[] args) {
int first = 85;
int second = 90;
double average = (first + second) / 2; // 87.0, not 87.5
System.out.println("Average: " + average);
System.out.println("Total: " + first + second); // "Total: 8590"
}
}Why does this happen?
In (first + second) / 2 both sides are int, so Java does integer division and gets 87; storing it in a double happens after the division, so the lost .5 never comes back. On the second line + is evaluated left to right: "Total: " + 85 becomes a String, and then 90 is glued onto that string.
Core concept: every operator has a type and an order
The arithmetic operators are + - * / %. When both sides are int the result is int, so / drops the fraction and truncates toward zero (7 / 2 is 3, -7 / 2 is -3). % gives the remainder, and its sign follows the left operand (-7 % 2 is -1). If one side is a double, Java promotes the other side to double before calculating, so 7 / 2.0 is 3.5. byte, short and char values are also promoted to at least int before any arithmetic.
An int holds values from -2,147,483,648 to 2,147,483,647. Go past the top and Java does not raise an error: the value wraps around to the other end, so Integer.MAX_VALUE + 1 is -2147483648. Dividing an int by zero throws an ArithmeticException, but dividing a double by zero quietly gives Infinity or NaN.
The comparison operators (== != < <= > >=) produce a boolean. Keep = (assign) and == (compare) apart. The logical operators && (AND), || (OR) and ! (NOT) combine booleans.
&& and || short-circuit. In a && b, if a is false the answer is already false, so b is never evaluated. That is why the guard name != null && name.length() > 3 does not throw a NullPointerException when name is null. Used on booleans, & and | always evaluate both sides.
Finally there is precedence: * / % bind tighter than + -, comparisons bind tighter than &&, and && binds tighter than ||. With ++ and --, the prefix form (++i) increments first and then gives the value, while the postfix form (i++) gives the old value and then increments. Compound assignments like += also cast the result back to the variable's type for you. When in doubt, add parentheses; they help the next reader as much as the compiler.
| Expression | Result | Why |
|---|---|---|
| 7 / 2 | 3 | int / int is int |
| 7 / 2.0 | 3.5 | 2.0 is a double, so 7 is promoted |
| -7 % 2 | -1 | sign follows the left operand |
| "A" + 1 + 2 | "A12" | left to right, already a String |
| 1 + 2 + "A" | "3A" | the two numbers are added first |
public class Main {
public static void main(String[] args) {
int i = 5;
int a = i++; // a gets 5, then i becomes 6
int b = ++i; // i becomes 7, then b gets 7
System.out.println(a + " " + b + " " + i);
byte small = 10;
small += 5; // OK: += casts back to byte (small = small + 5 would not compile)
System.out.println(small);
String name = null;
boolean longName = name != null && name.length() > 3; // right side skipped
System.out.println("Long name? " + longName);
}
}- Group by precedence and parentheses
- Look at both operand types
- Promote to int or double if needed
- Compute in that type (truncate, wrap)
- && / || evaluate the right only if needed
The variable you store into only matters after the calculation: putting int / int into a double does not bring the fraction back.
General pattern
type result = left OP right; // + - * / %
boolean test = value COMPARE limit; // == != < <= > >=
boolean both = conditionA && conditionB; // also ||, !
variable += amount; // also -= *= /= %=
double exact = intValue / (double) other;
long big = intValue * 1L * otherInt; // widen before multiplying
type choice = condition ? valueIfTrue : valueIfFalse;An operator sits between two operands, and the result type depends on the operand types. Cast with (double) before dividing when you need a fraction, and widen to long with 1L before multiplying large numbers. ? : is an operator that picks one of two values based on a condition.
Example: price checks and packing boxes
The first half calculates a discounted price and checks whether the item can be bought. The second half packs 7 cookies into boxes of 3 to show how / and % work as a pair, and the last line deliberately falls into the string concatenation trap.
public class Main {
public static void main(String[] args) {
int price = 100;
int discount = 15;
int finalPrice = price - discount;
boolean isAffordable = finalPrice <= 90;
boolean hasStock = true;
System.out.println("Final price: " + finalPrice);
System.out.println("Can buy: " + (isAffordable && hasStock));
int cookies = 7;
int boxSize = 3;
System.out.println("Full boxes: " + cookies / boxSize);
System.out.println("Left over: " + cookies % boxSize);
System.out.println("Exact share: " + cookies / (double) boxSize);
System.out.println("Wrong grouping: " + cookies + boxSize);
}
}Code breakdown
- Line 7
boolean isAffordable = finalPrice <= 90;<= is a comparison, so its result is true or false. 85 <= 90, so true is stored in a boolean variable.
- Line 11
System.out.println("Can buy: " + (isAffordable && hasStock));&& is true only when both sides are true. The parentheses matter: without them "Can buy: " + isAffordable would become a String first, and String && boolean is a compile error.
- Lines 15-16
System.out.println("Full boxes: " + cookies / boxSize);/ binds tighter than +, so 7 / 3 is calculated first. It is int division, giving 2 full boxes, and the next line uses 7 % 3 for the 1 cookie left over. Together, / and % answer "how many full groups, and how many remain" exactly.
- Line 17
cookies / (double) boxSizeThe (double) cast turns boxSize into 3.0, so cookies is promoted too and the result is 2.3333333333333335. The final digit comes from how a double is stored in binary.
- Line 18
System.out.println("Wrong grouping: " + cookies + boxSize);Without parentheses this runs left to right: it becomes "Wrong grouping: 7" and then "3" is appended, so it prints 73, not 10. Writing (cookies + boxSize) would print 10.
Final price: 85
Can buy: true
Full boxes: 2
Left over: 1
Exact share: 2.3333333333333335
Wrong grouping: 73Overflow and division by zero
Overflow is dangerous because it is silent. Calculate large values such as money totals, millisecond timestamps or file sizes in int, and the result can turn negative. There are two defences: switch to long before calculating (max + 1L), or use Math.addExact() and Math.multiplyExact(), which throw an exception on overflow. For money, avoid double and use long (in cents) or BigDecimal.
public class Main {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
System.out.println(max + 1); // wraps to the minimum
long safe = max + 1L; // long arithmetic, no wrap
System.out.println(safe);
System.out.println(-7 / 2 + " " + -7 % 2); // truncates toward zero
System.out.println(1.0 / 0); // double: Infinity
try {
System.out.println(Math.addExact(max, 1));
} catch (ArithmeticException e) {
System.out.println("addExact: " + e.getMessage());
}
try {
System.out.println(10 / 0);
} catch (ArithmeticException e) {
System.out.println("10 / 0: " + e.getMessage());
}
}
}This prints -2147483648, 2147483648, -3 -1, Infinity, addExact: integer overflow and 10 / 0: / by zero, in that order. try / catch is covered properly in the exceptions lesson; here it only keeps the program running.
In real projects
Where this shows up in real projects
Pagination is the classic use of / and %. To show 95 items at 10 per page you need (95 + 10 - 1) / 10 = 10 pages, and the last page holds 95 % 10 = 5 items. The same % stripes table rows (i % 2 == 0), spreads IDs across shards or buckets, and turns seconds into minutes and seconds (total / 60, total % 60).
Short-circuit guards appear in nearly every backend codebase: user != null && user.isActive(), list.isEmpty() || list.get(0) ..., and so on. Overflow has caused real incidents too, where a counter passed the int limit and negative IDs or negative totals appeared. That is why Java APIs return timestamps (System.currentTimeMillis()) and file sizes as long. In code that handles money, reviewers routinely ask for long cents or BigDecimal instead of double.
Common mistakes
Common mistakes
1. Casting after the division
(double) (sum / count) divides as int first and only then converts, so the fraction is already gone. Write (double) sum / count or sum / (double) count so the cast happens before the division.
2. Writing = inside a boolean condition
For an int, if (count = 5) is a compile error, so you notice at once. For a boolean, if (isAdmin = true) compiles, assigns true and is therefore always true, which is a genuine permission bug. Just write if (isAdmin).
3. Putting the guard in the wrong order
name.length() > 0 && name != null puts the null check second, so a null name throws a NullPointerException on the left side already. Short-circuiting works left to right, so the protective check always goes on the left. Using & instead of && also loses the protection, because both sides are evaluated.
Mini challenge
Mini challenge: shipping box calculator
For an online shop, write the box-packing calculation and the free-shipping check using operators only (no if statements).
- boxesNeeded(items, perBox): returns the number of boxes, rounding up with integer division
- lastBoxCount(items, perBox): returns how many items the last box holds (perBox when full), using % and ? :
- freeShipping(total, remoteArea): true only when total >= 50.0 and the area is not remote
- Print the results for 23 items, 6 per box, 2.5 each
public class Main {
static int boxesNeeded(int items, int perBox) {
// TODO: round up without using double
return 0;
}
static int lastBoxCount(int items, int perBox) {
// TODO: use % and the ? : operator
return 0;
}
static boolean freeShipping(double total, boolean remoteArea) {
// TODO: combine two conditions
return false;
}
public static void main(String[] args) {
// TODO: 23 items, 6 per box, 2.5 each; print all results
}
}Expected: The program prints these six lines: Boxes: 4 Last box holds: 5 Total: 57.5 Free shipping: true Free shipping (remote): false Boxes for 24: 4
Show hint
Round up with (items + perBox - 1) / perBox. A % result of 0 means the last box is full. items * 2.5 is already a double.
Show solution
public class Main {
static int boxesNeeded(int items, int perBox) {
return (items + perBox - 1) / perBox;
}
static int lastBoxCount(int items, int perBox) {
int rest = items % perBox;
return rest == 0 ? perBox : rest;
}
static boolean freeShipping(double total, boolean remoteArea) {
return total >= 50.0 && !remoteArea;
}
public static void main(String[] args) {
int items = 23;
int perBox = 6;
double total = items * 2.5;
System.out.println("Boxes: " + boxesNeeded(items, perBox));
System.out.println("Last box holds: " + lastBoxCount(items, perBox));
System.out.println("Total: " + total);
System.out.println("Free shipping: " + freeShipping(total, false));
System.out.println("Free shipping (remote): " + freeShipping(total, true));
System.out.println("Boxes for 24: " + boxesNeeded(24, perBox));
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- int / int is an int: cast with (double) before dividing when you need a fraction; % gives the remainder.
- int overflow wraps around without an error, so use long or Math.addExact() for large values.
- && and || short-circuit, so put the null check on the left.
- + runs left to right and turns into concatenation once a String appears, so wrap numeric sums in parentheses.