Operators in Java
Learn how to perform operations and make calculations
Think of operators like tools in a toolbox! Just like you use a hammer to nail things, a screwdriver to turn screws, Java uses operators to add numbers, compare values, and make decisions. Each operator is a special symbol that tells Java what to do!
➕ Arithmetic Operators (Math Tools)
For doing math - like a calculator!
Addition
5 + 3 = 8Adds two numbers
Subtraction
10 - 4 = 6Subtracts second from first
Multiplication
6 * 7 = 42Multiplies two numbers
Division
20 / 4 = 5Divides first by second
Modulus (Remainder)
10 % 3 = 1Gets remainder after division
📝 Code Examples: Arithmetic Operators
public class ArithmeticDemo { public static void main(String[] args) { int a = 20; int b = 7; // Basic arithmetic System.out.println("Addition: " + (a + b)); // 27 System.out.println("Subtraction: " + (a - b)); // 13 System.out.println("Multiplication: " + (a * b)); // 140 System.out.println("Division: " + (a / b)); // 2 (integer division!) System.out.println("Modulus: " + (a % b)); // 6 (remainder) // Integer vs Double division System.out.println("Integer: " + (5 / 2)); // 2 System.out.println("Double: " + (5.0 / 2.0)); // 2.5 // Modulus use cases int num = 17; if (num % 2 == 0) { System.out.println(num + " is even"); } else { System.out.println(num + " is odd"); // This runs } // Check if divisible by 3 if (num % 3 == 0) { System.out.println("Divisible by 3"); } else { System.out.println("Not divisible by 3"); // This runs } }}⚖️ Comparison Operators (Comparing Things)
For checking if things are equal, bigger, or smaller
Equal to
5 == 5 → trueChecks if values are equal
Not equal to
5 != 3 → trueChecks if values are different
Greater than
8 > 5 → trueChecks if first is bigger
Less than
3 < 7 → trueChecks if first is smaller
Greater than or equal
5 >= 5 → trueChecks if first is bigger or same
Less than or equal
4 <= 6 → trueChecks if first is smaller or same
📝 Code Examples: Comparison Operators
public class ComparisonDemo { public static void main(String[] args) { int age = 18; int votingAge = 18; int drivingAge = 16; // Equal to System.out.println(age == votingAge); // true System.out.println(age == drivingAge); // false // Not equal to System.out.println(age != drivingAge); // true System.out.println(age != votingAge); // false // Greater than / Less than System.out.println(age > drivingAge); // true (18 > 16) System.out.println(age < votingAge); // false (18 < 18) // Greater/Less than or equal System.out.println(age >= votingAge); // true (18 >= 18) System.out.println(age <= votingAge); // true (18 <= 18) // Real-world example int score = 85; if (score >= 90) { System.out.println("Grade: A"); } else if (score >= 80) { System.out.println("Grade: B"); // This runs } else if (score >= 70) { System.out.println("Grade: C"); } else { System.out.println("Grade: F"); } // ⚠️ WARNING: Don't use == for Strings! String name1 = "Alice"; String name2 = "Alice"; System.out.println(name1 == name2); // May work (string pool) System.out.println(name1.equals(name2)); // ✓ ALWAYS use .equals() }}🧠 Logical Operators (Making Decisions)
For combining true/false conditions
AND
true && false → falseBoth must be true
OR
true || false → trueAt least one must be true
NOT
!true → falseFlips true to false and vice versa
📝 Code Examples: Logical Operators
public class LogicalDemo { public static void main(String[] args) { int age = 25; boolean hasLicense = true; boolean hasInsurance = false; // AND (&&) - Both must be true if (age >= 18 && hasLicense) { System.out.println("Can drive"); // This runs } if (hasLicense && hasInsurance) { System.out.println("Can drive legally"); // Won't run } // OR (||) - At least one must be true if (age < 18 || !hasLicense) { System.out.println("Cannot drive"); } else { System.out.println("Can drive"); // This runs } // NOT (!) - Flips the value System.out.println(!hasLicense); // false System.out.println(!hasInsurance); // true // Complex example int score = 75; boolean hasBonus = true; if ((score >= 70 && score < 80) || hasBonus) { System.out.println("Passed!"); // This runs } // Short-circuit evaluation int x = 5; // && stops if first is false (doesn't check second) if (x > 10 && x++ < 20) { // x++ never runs! System.out.println("Inside if"); } System.out.println("x = " + x); // Still 5! // || stops if first is true (doesn't check second) if (x < 10 || x++ > 20) { // x++ never runs! System.out.println("Inside if"); // This runs } System.out.println("x = " + x); // Still 5! }}📥 Assignment Operators (Storing Values)
For putting values into variables
Assign
x = 5Puts value into variable
Add and assign
x += 3 (same as x = x + 3)Adds then stores
Subtract and assign
x -= 2 (same as x = x - 2)Subtracts then stores
Multiply and assign
x *= 4 (same as x = x * 4)Multiplies then stores
Divide and assign
x /= 2 (same as x = x / 2)Divides then stores
Modulus and assign
x %= 3 (same as x = x % 3)Gets remainder then stores
📝 Code Examples: Assignment Operators
public class AssignmentDemo { public static void main(String[] args) { int score = 100; // Simple assignment // Add and assign score += 10; // Same as: score = score + 10 System.out.println("Score: " + score); // 110 // Subtract and assign score -= 5; // Same as: score = score - 5 System.out.println("Score: " + score); // 105 // Multiply and assign score *= 2; // Same as: score = score * 2 System.out.println("Score: " + score); // 210 // Divide and assign score /= 7; // Same as: score = score / 7 System.out.println("Score: " + score); // 30 // Modulus and assign score %= 7; // Same as: score = score % 7 System.out.println("Score: " + score); // 2 // Real-world example: Game score int playerScore = 0; playerScore += 50; // Collected coin: +50 playerScore += 100; // Defeated enemy: +100 playerScore -= 20; // Got hit: -20 playerScore *= 2; // Power-up: double score System.out.println("Final score: " + playerScore); // 260 }}1️⃣ Unary Operators (Working with One Value)
Operators that work on a single value
Increment
x++ (adds 1 to x)Increases by 1
Decrement
x-- (subtracts 1 from x)Decreases by 1
Unary plus
+5Positive number
Unary minus
-5Negative number
Logical NOT
!true → falseFlips boolean value
📝 Code Examples: Unary Operators
public class UnaryDemo { public static void main(String[] args) { int count = 5; // Post-increment (use then increase) System.out.println(count++); // Prints 5, then becomes 6 System.out.println(count); // Now 6 // Pre-increment (increase then use) System.out.println(++count); // Becomes 7, then prints 7 System.out.println(count); // Still 7 // Post-decrement (use then decrease) System.out.println(count--); // Prints 7, then becomes 6 System.out.println(count); // Now 6 // Pre-decrement (decrease then use) System.out.println(--count); // Becomes 5, then prints 5 System.out.println(count); // Still 5 // Unary minus/plus int num = 10; System.out.println(+num); // 10 System.out.println(-num); // -10 System.out.println(num); // Still 10 (doesn't change original) // Logical NOT boolean isReady = true; System.out.println(!isReady); // false System.out.println(isReady); // Still true // Real example: Loop counter for (int i = 0; i < 5; i++) { System.out.println("Count: " + i); } // i++ increases after each iteration }}3️⃣ Ternary Operator (Quick If-Else)
A shortcut for simple if-else statements
public class TernaryDemo { public static void main(String[] args) { // Syntax: condition ? valueIfTrue : valueIfFalse int age = 20; String status = (age >= 18) ? "Adult" : "Minor"; System.out.println(status); // Adult // Instead of: // if (age >= 18) { // status = "Adult"; // } else { // status = "Minor"; // } // More examples int score = 85; String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : (score >= 70) ? "C" : "F"; System.out.println("Grade: " + grade); // B // Finding max int a = 15, b = 20; int max = (a > b) ? a : b; System.out.println("Max: " + max); // 20 // Even or odd int num = 7; String result = (num % 2 == 0) ? "Even" : "Odd"; System.out.println(num + " is " + result); // 7 is Odd }}🎯 Operator Precedence (Order of Operations)
Like PEMDAS in math - which operation happens first?
- 1. Parentheses:
()- Highest priority - 2. Unary:
++ -- ! - + - 3. Multiplication/Division:
* / % - 4. Addition/Subtraction:
+ - - 5. Comparison:
< > <= >= - 6. Equality:
== != - 7. Logical AND:
&& - 8. Logical OR:
|| - 9. Ternary:
? : - 10. Assignment:
= += -= *= /= %=- Lowest priority
public class PrecedenceDemo { public static void main(String[] args) { // Without parentheses int result = 5 + 3 * 2; System.out.println(result); // 11 (not 16!) // Multiplication happens first: 3 * 2 = 6, then 5 + 6 = 11 // With parentheses result = (5 + 3) * 2; System.out.println(result); // 16 // Parentheses first: 5 + 3 = 8, then 8 * 2 = 16 // Complex expression result = 10 + 5 * 2 - 3; System.out.println(result); // 17 // Steps: 5 * 2 = 10, then 10 + 10 = 20, then 20 - 3 = 17 // With parentheses for clarity result = ((10 + 5) * 2) - 3; System.out.println(result); // 27 // Steps: 10 + 5 = 15, then 15 * 2 = 30, then 30 - 3 = 27 // Tip: Use parentheses to make your code clearer! }}💼 Interview Tips
- 💡Know the difference between == (comparison) and = (assignment)
- 💡Remember: && requires BOTH to be true, || requires AT LEAST ONE
- 💡Integer division truncates: 5/2 = 2, not 2.5
- 💡Understand ++i (pre-increment) vs i++ (post-increment)
- 💡Use parentheses to make operator precedence clear
- 💡Be careful with floating-point comparisons due to precision
- 💡String comparison: use .equals(), not ==
⚠️ Common Mistakes
- ✗Using = instead of == for comparison (if (x = 5) instead of if (x == 5))
- ✗Forgetting integer division truncates decimals
- ✗Using == to compare Strings (use .equals() method)
- ✗Not understanding short-circuit evaluation (&&, ||)
- ✗Confusing ++i and i++ in expressions
- ✗Dividing by zero (causes runtime error)
- ✗Mixing up ! (NOT) operator placement