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

    Practice all arithmetic operators, including integer division and modulo. Try changing the numbers!

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // === ARITHMETIC OPERATORS IN ACTION ===
    
    console.log("=== Java Arithmetic Operators ===");
    console.log("");
    
    let a = 10, b = 3;
    console.log("a = " + a + ", b = " + b);
    console.log("");
    
    // Basic operations
    console.log("1️⃣ BASIC ARITHMETIC:");
    console.log("  a + b = " + (a + b) + "  (addition)");
    console.log("  a - b = " + (a - b) + "  (subtraction)");
    console.log("  a * b = " + (a * b) + " (multiplication)");
    console.log("  a / b = " + Math.
    ...

    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

    See how comparison and logical operators produce true/false results. Try changing the values!

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // === COMPARISON & LOGICAL OPERATORS ===
    
    console.log("=== Comparison Operators ===");
    console.log("");
    
    let x = 5, y = 10;
    console.log("x = " + x + ", y = " + y);
    console.log("  x == y:  " + (x === y) + "  (equal?)");
    console.log("  x != y:  " + (x !== y) + "  (not equal?)");
    console.log("  x > y:   " + (x > y) + "  (greater?)");
    console.log("  x < y:   " + (x < y) + "   (less?)");
    console.log("  x >= 5:  " + (x >= 5) + "   (greater or equal?
    ...

    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

    Use operators to build a grade calculator — a real-world program that uses math, comparison, and logic!

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // === MINI PROJECT: Grade Calculator ===
    
    console.log("╔══════════════════════════════════╗");
    console.log("║     GRADE CALCULATOR             ║");
    console.log("╚══════════════════════════════════╝");
    console.log("");
    
    // Student scores (try changing these!)
    let math = 85;
    let science = 92;
    let english = 78;
    let history = 88;
    
    console.log("📊 Scores:");
    console.log("  Math:    " + math);
    console.log("  Science: " + science);
    console.log("  Eng
    ...

    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