Skip to main content

    Lesson 3 • Beginner

    Java Operators

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

    What You'll Learn in This Lesson

    • Arithmetic operators: +, -, *, /, % and when each is useful
    • The integer division gotcha that trips up every beginner
    • Comparison operators for making decisions: ==, !=, >, <
    • Logical operators for combining conditions: &&, ||, !
    • Assignment shortcuts: +=, -=, *=, /=
    • Operator precedence — why order matters

    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:

    • Arithmetic: Do math (+, -, *, /, %)
    • Comparison: Compare values (==, !=, >, <)
    • Logical: Combine true/false (&&, ||, !)
    • Assignment: Store values (=, +=, -=)

    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

    Real-world uses:

    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
    Try It: Arithmetic Operators
    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));
        }
    }
    Output
    a = 10, b = 3
    a + b = 13
    a - b = 7
    a * b = 30
    a / b = 3  (integer division!)
    a % b = 1  (modulo/remainder)
    7 / 2   = 3   (not 3.5!)
    7.0 / 2 = 3.5 (use a double)
    Is 8 even? true
    Last digit of 12345: 5
    3725 seconds = 62 min 5 sec
    2 + 3 * 4 = 14
    (2 + 3) * 4 = 20
    This is real code — run it for free atonecompiler.com/javaor in your own editor.

    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?

    Real-world example:

    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

    Practical example:

    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

    🧠 Tip:

    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.

    Try It: Comparison and Logical Operators
    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);
        }
    }
    Output
    x == y:  false
    x != y:  true
    x > y:   false
    x < y:   true
    x >= 5:  true
    x <= 4:  false
    Can drive? false (isInsured is false)
    Gets discount? false
    !hasLicense = false
    Login valid? true
    score += 10 -> 110
    score *= 2  -> 220
    This is real code — run it for free atonecompiler.com/javaor in your own editor.

    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

    🧠 Tip:

    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.

    ❌ Never do this:

    if (name == "Alice") {
      // May fail unexpectedly!
    }

    ✅ Always do this:

    if (name.equals("Alice")) {
      // Safe and reliable!
    }
    Try It: Build a Grade Calculator
    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));
        }
    }
    Output
    Total: 343
    Average: 85.8
    With integer division: 85 (wrong!)
    Average 85.8 -> Grade: B
    Passed:          true
    Honors:          false
    All subjects 60+: true
    Math even? false
    This is real code — run it for free atonecompiler.com/javaor in your own editor.

    Common Beginner Mistakes

    • = vs ==: = is assignment ("put this value in"), == is comparison ("are these equal?"). Writing if (x = 5) is wrong — use if (x == 5)
    • Integer division: 1 / 3 is 0, not 0.33. Always make at least one operand a double when you want decimals
    • String comparison with ==: == compares memory addresses for objects. Always use .equals() for String content comparison
    • Division by zero: int x = 10 / 0; crashes with ArithmeticException. (But 10.0 / 0 gives Infinity — different behaviour!)
    • Forgetting precedence: 2 + 3 * 4 is 14, not 20. Use parentheses when in doubt: (2 + 3) * 4

    💡 Pro Tips

    • 💡 Use parentheses liberally: Even when not needed, they make your code clearer. (a * b) + c is easier to read than a * b + c
    • 💡 Modulo for cycling: index % arraySize automatically wraps around — perfect for circular buffers, rotating through options, etc.
    • 💡 Short-circuit for safety: obj != null && obj.method() prevents NullPointerException. Java won't call the method if obj is null
    • 💡 Ternary operator preview: int max = (a > b) ? a : b; is a one-line if/else. You'll learn this in the next lesson!

    📋 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.

    Next up: Control Flow — use these operators inside if statements and switch cases to make your programs decide and react to different situations.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service