Operators

Reviewed & published by Brayan K

Operators are the verbs of programming — they perform actions on your data. Learn how to do math, compare values, and combine conditions.

Part of the free Java course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.

What You'll Learn in This Lesson

1️⃣ What Are Operators? (Plain English)

An operator is a symbol that tells Java to perform an action on your data. You already know some from math class: +, -, *.

💡 Analogy: Think of operators like buttons on a calculator. Each button performs a specific action. But Java's calculator has some extra buttons (like % and &&) and some quirks (like integer division) that you need to know about.

Java has several categories of operators:

Let's go through each one with examples.

2️⃣ Arithmetic Operators — Doing Math

These work mostly like you'd expect from math class, with one big exception:

int a = 10, b = 3;

a + b   →  13    // Addition
a - b   →  7     // Subtraction
a * b   →  30    // Multiplication
a / b   →  3     // Division (⚠️ NOT 3.33!)
a % b   →  1     // Modulo (remainder)

⚠️ THE INTEGER DIVISION TRAP

This is the #1 math gotcha in Java. When you divide two int values, Java performs integer division — it throws away the decimal part completely (no rounding!).

int result = 7 / 2;     // Result: 3 (not 3.5!)
int result2 = 1 / 3;    // Result: 0 (not 0.33!)
int result3 = 99 / 100; // Result: 0 (not 0.99!)

Fix: Make at least one number a double:

double result = 7.0 / 2;       // 3.5 ✅
double result2 = (double) 7 / 2; // 3.5 ✅
double result3 = 7 / 2.0;      // 3.5 ✅

3️⃣ The Modulo Operator (%) — The Most Underrated Operator

The % (modulo) operator gives you the remainder after division. It seems simple, but it's incredibly powerful:

10 % 3  →  1    // 10 ÷ 3 = 3 remainder 1
7 % 2   →  1    // 7 ÷ 2 = 3 remainder 1
8 % 2   →  0    // 8 ÷ 2 = 4 remainder 0
15 % 5  →  0    // 15 ÷ 5 = 3 remainder 0
PatternCodeWhat It Does
Check even/oddn % 2 == 0True if n is even
Get last digitn % 10Returns last digit of n
Wrap aroundindex % arrayLengthKeeps index in bounds
Time conversionseconds % 60Remaining seconds

💡 Example: Converting 3725 seconds to minutes and seconds:

int totalSeconds = 3725;
int minutes = totalSeconds / 60;  // 62 minutes
int seconds = totalSeconds % 60;  // 5 seconds
// Answer: 62 minutes and 5 seconds
public class Main {
    public static void main(String[] args) {
        int a = 10, b = 3;
        System.out.println("a = " + a + ", b = " + b);

        // Basic arithmetic
        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a * b = " + (a * b));
        System.out.println("a / b = " + (a / b) + "  (integer division!)");
        System.out.println("a % b = " + (a % b) + "  (modulo/remainder)");

        // Integer division trap
        System.out.println("7 / 2   = " + (7 / 2) + "   (not 3.5!)");
        System.out.println("7.0 / 2 = " + (7.0 / 2) + " (use a double)");

        // Modulo — practical uses
        System.out.println("Is 8 even? " + (8 % 2 == 0));
        System.out.println("Last digit of 12345: " + (12345 % 10));

        int totalSec = 3725;
        int mins = totalSec / 60;
        int secs = totalSec % 60;
        System.out.println(totalSec + " seconds = " + mins + " min " + secs + " sec");

        // Order of operations
        System.out.println("2 + 3 * 4 = " + (2 + 3 * 4));
        System.out.println("(2 + 3) * 4 = " + ((2 + 3) * 4));
    }
}

4️⃣ Comparison Operators — Asking Yes/No Questions

Comparison operators compare two values and return true or false. They're essential for making decisions in your programs (which you'll do in the next lesson with if statements).

int x = 5, y = 10;

x == y    →  false   // Equal to?
x != y    →  true    // Not equal to?
x > y     →  false   // Greater than?
x < y     →  true    // Less than?
x >= y    →  false   // Greater than or equal to?
x <= y    →  true    // Less than or equal to?
int age = 17;
boolean canVote = age >= 18;     // false
boolean isTeenager = age >= 13 && age <= 19;  // true

double balance = 50.0;
boolean canAfford = balance >= 29.99;  // true

5️⃣ Logical Operators — Combining Conditions

Logical operators let you combine multiple true/false conditions into one. There are three:

OperatorNameMeaningExample
&&ANDBoth must be trueage > 18 && hasID
||ORAt least one must be trueisVIP || hasCoupon
!NOTFlips true ↔ false!isBlocked
int age = 20;
boolean hasLicense = true;
boolean isInsured = false;

// Can this person drive?
boolean canDrive = age >= 16 && hasLicense && isInsured;
// false — all must be true, but isInsured is false

// Can they get a discount?
boolean getsDiscount = age < 18 || age > 65;
// false — neither condition is true for age 20

💡 Short-Circuit Evaluation: In false && anything, Java never evaluates anything because AND already can't be true. This is useful for safety:

// Safe — won't crash if name is null!
if (name != null && name.length() > 0) {
    // Only runs if name exists AND has content
}

6️⃣ Assignment Operators — Shortcuts for Changing Values

Instead of writing x = x + 5, Java has shortcuts:

int score = 100;

score += 10;   // score = score + 10  → 110
score -= 5;    // score = score - 5   → 105
score *= 2;    // score = score * 2   → 210
score /= 3;    // score = score / 3   → 70
score %= 6;    // score = score % 6   → 4

Pre vs Post Increment:

int a = 5;
int b = a++;   // b gets 5, THEN a becomes 6
// Post-increment: use the value first, then add 1

int c = 5;
int d = ++c;   // c becomes 6 first, THEN d gets 6
// Pre-increment: add 1 first, then use the value

When used alone on a line (i++;), pre and post increment do the same thing. The difference only matters when used inside another expression. When in doubt, put them on their own line.

public class Main {
    public static void main(String[] args) {
        int x = 5, y = 10;
        System.out.println("x == y:  " + (x == y));
        System.out.println("x != y:  " + (x != y));
        System.out.println("x > y:   " + (x > y));
        System.out.println("x < y:   " + (x < y));
        System.out.println("x >= 5:  " + (x >= 5));
        System.out.println("x <= 4:  " + (x <= 4));

        int age = 20;
        boolean hasLicense = true;
        boolean isInsured = false;

        // AND — all must be true
        boolean canDrive = age >= 16 && hasLicense && isInsured;
        System.out.println("Can drive? " + canDrive + " (isInsured is false)");

        // OR — at least one must be true
        boolean getsDiscount = age < 18 || age > 65;
        System.out.println("Gets discount? " + getsDiscount);

        // NOT — flips the result
        System.out.println("!hasLicense = " + (!hasLicense));

        // String comparison uses .equals(), not ==
        String username = "admin";
        boolean isValidUser = username.equals("admin");
        System.out.println("Login valid? " + isValidUser);

        // Assignment shortcuts
        int score = 100;
        score += 10;
        System.out.println("score += 10 -> " + score);
        score *= 2;
        System.out.println("score *= 2  -> " + score);
    }
}

7️⃣ Operator Precedence — Order Matters!

Just like in math, Java has rules about which operations happen first. Multiplication happens before addition unless you use parentheses:

int result1 = 2 + 3 * 4;      // 14 (not 20!)
int result2 = (2 + 3) * 4;    // 20 (parentheses force order)

boolean check = true || false && false;  // true
// && happens before ||, so: true || (false && false) → true || false → true

Precedence from highest to lowest:

PriorityOperatorsCategory
1 (highest)() ++ -- !Parentheses, unary
2* / %Multiplication, division
3+ -Addition, subtraction
4< > <= >=Comparison
5== !=Equality
6&&Logical AND
7||Logical OR
8 (lowest)= += -= *= /=Assignment

Don't try to memorize this whole table. Instead, use parentheses whenever you're unsure. (a + b) * c is clearer than relying on precedence rules. Your future self will thank you.

8️⃣ The == vs .equals() Trap (Strings)

This trips up every Java beginner. With numbers, == works perfectly. With Strings, it's dangerous:

// Numbers — == works fine
int a = 5, b = 5;
a == b   →  true  ✅

// Strings — == is UNRELIABLE
String s1 = new String("hello");
String s2 = new String("hello");
s1 == s2        →  false  ❌  (comparing memory addresses!)
s1.equals(s2)   →  true   ✅  (comparing actual text!)

💡 Why? For primitives (int, double, boolean), == compares the actual values. For objects (String, arrays), == compares whether they're the same object in memory — not whether they have the same content. Use .equals() for content comparison.

if (name == "Alice") {
  // May fail unexpectedly!
}
if (name.equals("Alice")) {
  // Safe and reliable!
}
public class Main {
    public static void main(String[] args) {
        int math = 85, science = 92, english = 78, history = 88;

        // Average — note 4.0 to force double division
        int total = math + science + english + history;
        double average = total / 4.0;
        System.out.println("Total: " + total);
        System.out.printf("Average: %.1f%n", average);

        // Integer division would be wrong here
        System.out.println("With integer division: " + (total / 4) + " (wrong!)");

        // Grade using comparison operators
        String grade;
        if (average >= 90) grade = "A";
        else if (average >= 80) grade = "B";
        else if (average >= 70) grade = "C";
        else if (average >= 60) grade = "D";
        else grade = "F";
        System.out.printf("Average %.1f -> Grade: %s%n", average, grade);

        // Logical operators
        boolean passed = average >= 60;
        boolean honors = average >= 90;
        boolean allPassing = math >= 60 && science >= 60
                && english >= 60 && history >= 60;
        System.out.println("Passed:          " + passed);
        System.out.println("Honors:          " + honors);
        System.out.println("All subjects 60+: " + allPassing);

        // Modulo: even/odd
        System.out.println("Math even? " + (math % 2 == 0));
    }
}
public class Main {
    public static void main(String[] args) {
        // 🎯 YOUR TURN — replace each ___ using the hint beside it.

        int cartons = 17;
        int perBox  = 5;

        // 1) Whole boxes: integer division throws the remainder away.
        int fullBoxes = cartons ___ perBox;      // 👉 replace ___ with /

        // 2) What is left over is the remainder.
        int leftOver  = cartons ___ perBox;      // 👉 replace ___ with %

        System.out.println("Full boxes: " + fullBoxes);
        System.out.println("Left over:  " + leftOver);

        // 3) To get decimals, one side must be a double — cast it.
        double exact = (___) cartons / perBox;   // 👉 replace ___ with double
        System.out.println("Exact:      " + exact);

        boolean needsExtraBox = leftOver > 0;

        // 4) BOTH conditions have to hold, so use the AND operator.
        boolean fitsOnPallet = fullBoxes <= 3 ___ leftOver < 4;  // 👉 replace ___ with &&

        System.out.println("Needs an extra box? " + needsExtraBox);
        System.out.println("Fits on one pallet? " + fitsOnPallet);

        int shipped = 0;
        // 5) Add fullBoxes to shipped in one step.
        shipped ___ fullBoxes;                   // 👉 replace ___ with +=
        shipped++;                                // the part-full box goes too
        System.out.println("Boxes shipped: " + shipped);
    }
}

Common Beginner Mistakes

💡 Pro Tips

📋 Quick Reference

CategoryOperatorsPrecedence
Unary++ -- ! (type)Highest
Multiplicative* / %High
Additive+ -Medium
Relational< > <= >= instanceofMedium-low
Equality== !=Low
Logical AND&&Lower
Logical OR||Lower still
Assignment= += -= *= /= %=Lowest

🎉 Lesson Complete!

Great work! You now understand all of Java's core operators — arithmetic, comparison, logical, and assignment. You know the integer division trap, how modulo works in real scenarios, and why == vs .equals() matters for Strings.

Practice quiz

What does the modulo operator % return?

  • The quotient of a division
  • The largest of two numbers
  • The remainder after division
  • A boolean

Answer: The remainder after division. % gives the remainder after division, e.g. 10 % 3 is 1.

What is the value of 10 % 3?

  • 1
  • 3
  • 0
  • 3.33

Answer: 1. 10 divided by 3 is 3 with a remainder of 1, so 10 % 3 is 1.

What does 2 + 3 * 4 evaluate to?

  • 20
  • 24
  • 9
  • 14

Answer: 14. Multiplication has higher precedence than addition: 3 * 4 = 12, then + 2 = 14.

What is the difference between = and ==?

  • They are identical
  • = assigns a value, == compares for equality
  • = compares, == assigns
  • Both compare values

Answer: = assigns a value, == compares for equality. = is assignment ('put this value in'); == is comparison ('are these equal?').

With int a = 5; int b = a++; what are b and a afterward?

  • b = 5, a = 6
  • b = 6, a = 6
  • b = 5, a = 5
  • b = 6, a = 5

Answer: b = 5, a = 6. Post-increment uses the value first (b = 5), then increments a to 6.

What is the result of 7.0 / 2?

  • 3
  • 4
  • 3.5
  • 3.0

Answer: 3.5. Because one operand is a double, this is floating-point division, giving 3.5.

For the && (AND) operator, when is the result true?

  • When at least one side is true
  • Only when both sides are true
  • When both sides are false
  • Always

Answer: Only when both sides are true. && is true only when both operands are true.

What does !hasLicense evaluate to when hasLicense is true?

  • true
  • null
  • An error
  • false

Answer: false. The NOT operator ! flips the boolean, so !true is false.

After int score = 100; score += 10; score *= 2; what is score?

  • 110
  • 220
  • 120
  • 200

Answer: 220. score becomes 110, then 110 * 2 = 220.

Why should you avoid == when comparing String objects?

  • It is slower
  • It does not compile
  • It compares memory addresses, not text content
  • It only works on numbers

Answer: It compares memory addresses, not text content. For objects, == compares references (memory addresses); use .equals() to compare actual text.

Continue this course