Unit 2 · Java Fundamentals · 8 min
Operators in Java
Operators are symbols that perform work on values: arithmetic (+ - * / %), relational (> < ==), logical (&& || !) and assignment (= += -=).
Why this matters
Every calculation, every condition and every loop you write depends on operators.
Example
Java
public class Operators {
public static void main(String[] args) {
int a = 17, b = 5;
System.out.println("Sum: " + (a + b));
System.out.println("Division: " + (a / b)); // integer division
System.out.println("Remainder: " + (a % b));
System.out.println("a > b ? " + (a > b));
System.out.println("Both true? " + (a > b && b > 0));
a += 3; // same as a = a + 3
System.out.println("a after += 3: " + a);
}
}Output
Sum: 22 Division: 3 Remainder: 2 a > b ? true Both true? true a after += 3: 20
Step by step
- 1`a / b` with two ints gives 3, not 3.4 — the decimal part is thrown away.
- 2`a % b` gives the remainder, 2. This is very useful for even/odd checks.
- 3`a > b` produces a boolean, true or false.
- 4`&&` is logical AND: true only when both sides are true.
- 5`a += 3` is shorthand for `a = a + 3`.
Key points
- int / int gives an int — cast to double for decimals
- % gives remainder, perfect for even/odd and digit problems
- == compares values for primitives; use .equals() for Strings
- && and || short-circuit: the right side may not be evaluated
Common mistakes
- Using = (assignment) where == (comparison) is needed
- Expecting 17/5 to be 3.4 without casting
- Comparing Strings with == instead of .equals()
Try it yourself
- Check whether a number is even using %.
- Find the average of three int marks correctly as a decimal.