Lesson 3 of 23
In progress
Operators and expressions
Arithmetic, comparison, logical and assignment operators, the integer division trap, and short-circuit evaluation that can hide a null.
Operators are where a program starts making decisions. Most of them behave as you expect; a handful have rules that produce wrong answers quietly, and those are worth knowing by name.
What you will learn
- Use arithmetic and assignment operators, including compound forms.
- Predict integer division, overflow and the remainder sign.
- Rely on short-circuit evaluation deliberately.
Arithmetic
int a = 7;
int b = 2;
System.out.println(a + b); // 9
System.out.println(a - b); // 5
System.out.println(a * b); // 14
System.out.println(a / b); // 3, not 3.5
System.out.println(a % b); // 1
Integer division truncates toward zero, so -7 / 2 is -3, not -4. The remainder takes the sign of the dividend, so -7 % 2 is -1. That matters when you compute page numbers or check divisibility with negative values.
To get a decimal result, at least one operand must be a floating-point value: a / 2.0 or (double) a / b.
Overflow
int max = Integer.MAX_VALUE;
System.out.println(max + 1); // -2147483648
Java’s integer types wrap on overflow, without an exception. A loop that counts up to a very large number can silently go negative. Math.addExact throws instead, which is worth using where an overflow would be a bug rather than a curiosity.
Long arithmetic is less likely to overflow and still possible. When totals can exceed a few billion, use long from the start: widening later means changing every signature that touches the value.
Compound assignment and increment
int total = 10;
total += 5; // 15
total -= 3; // 12
total *= 2; // 24
total /= 4; // 6
int i = 0;
int before = i++; // 0, then i becomes 1
int after = ++i; // i becomes 2, after is 2
i++ returns the old value and then increments; ++i increments first. In a standalone statement the two are identical, so prefer the standalone form and avoid x = i++ + ++i, which is legal and unreadable.
Comparison and equality
int x = 5;
System.out.println(x == 5); // true
System.out.println(x != 4); // true
System.out.println(x >= 5); // true
For objects, == compares references. equals compares content, and not every class overrides it, so the default is still reference equality. Strings, boxed primitives and the collection classes override it; your own classes do not until you write the method.
Logical operators
boolean hasStock = true;
boolean isMember = false;
System.out.println(hasStock && isMember); // false
System.out.println(hasStock || isMember); // true
System.out.println(!hasStock); // false
&& and || short-circuit: the right side is evaluated only when the left does not decide the result.
if (name != null && name.length() > 0) {
// safe: length() is not called when name is null
}
That is the idiom that makes null checks readable. The reverse order throws.
& and | on booleans evaluate both sides. They are occasionally useful when the second call has a side effect, which is itself a sign to restructure the code.
Ternary and null-coalescing
int qty = 0;
String label = qty == 0 ? "out of stock" : "in stock";
String name = null;
String display = name != null ? name : "anonymous";
The ternary is an expression, so it can be assigned or passed. Keep it to one line; nested ternaries are a readability tax.
Bitwise operators, briefly
&, |, ^ and ~ on integers operate on individual bits, and <<, >> shift them. You will use them for flags, hashing or low-level work; for ordinary logic, use the boolean forms.
One useful idiom: (n & 1) == 1 tests whether an integer is odd, which works for negative numbers where % can surprise.
Precedence
Multiplication before addition, comparison before logical, assignment last. The table is long enough that nobody remembers it accurately, so parenthesise when the expression mixes kinds:
boolean eligible = (age >= 18) && (income > 0);
The parentheses are not required. They are how a reader knows the intent without consulting a table.
A worked example
public class Shipping {
public static void main(String[] args) {
long orderPaise = 45_000L;
boolean member = true;
int items = 3;
boolean freeShipping = member || orderPaise >= 50_000L;
long shippingPaise = freeShipping ? 0L : 4_900L;
long totalPaise = orderPaise + shippingPaise;
System.out.println("free: " + freeShipping);
System.out.println("total rupees: " + totalPaise / 100.0);
System.out.println("per item: " + totalPaise / items / 100.0);
}
}
The last line divides twice with a long first: totalPaise / items is integer division, then the division by 100.0 produces the decimal. Doing it in the other order gives the same result here and a different one in general, which is why the order is worth thinking about.
Writing if (name.length() > 0 || name == null), which throws before the null check can help. Put the null test first and use &&: name != null && name.length() > 0.
Compute a cart total from three prices in paise, apply a 10 percent discount when the total exceeds 100000 paise, and print the total in rupees with two decimals.
Show solution
public class Cart { public static void main(String[] args) { long a = 45_000L; long b = 32_500L; long c = 40_000L; long total = a + b + c; boolean discounted = total > 100_000L; long payable = discounted ? total - (total * 10 / 100) : total; System.out.println("subtotal: " + total / 100.0); System.out.println("discount applied: " + discounted); System.out.println("payable: " + payable / 100.0); } } total * 10 / 100 keeps the arithmetic in long and truncates the discount to whole paise, which is the conservative choice for a merchant. Printing with / 100.0 produces the decimal form without changing the stored value.
Recap
- Integer division truncates and overflow wraps silently; use a wider type or
Math.addExact. &&and||short-circuit, which is what makes a null check safe.- Parenthesise mixed expressions and avoid increment inside larger expressions.
Next, strings and reading input, the two things every first program needs.
Why is 0.1 + 0.2 not 0.3?
Does != work on strings?
Progress is saved in this browser only. No account, no email.