Operators
Overview
Operators are special symbols that do the actual 'work' in your program. They perform math, compare values, or combine logic. Think of them like the buttons on a calculator (`+`, `-`, `=`, etc.), but much more powerful.
Without operators, variables would just sit there doing nothing. Operators allow us to calculate total prices, check if a password is correct, and make decisions.
1. Arithmetic Operators
Used for standard math: addition (`+`), subtraction (`-`), multiplication (`*`), and division (`/`). There is also a special one called Modulo (`%`) which gives you the remainder of a division.
2. Assignment Operators
The equals sign (`=`) assigns a value. We also have shortcuts like `+=` which means 'add this to the current value'.
3. Relational & Logical Operators
Relational operators compare two things (`>` , `<`, `==`). Logical operators combine multiple conditions, like 'AND' (`&&`), 'OR' (`||`), and 'NOT' (`!`).
Syntax
Modulo (`%`) is incredibly useful for finding out if a number is even or odd.
int x = 10;
int y = 3;
int sum = x + y; // 13
int quotient = x / y; // 3 (integer division drops the decimal!)
int remainder = x % y; // 1 (because 10 divided by 3 is 9, remainder 1)Combine conditions to make complex rules.
int age = 20;
boolean hasTicket = true;
// AND (&&): BOTH must be true
boolean canEnterMovie = (age >= 18) && hasTicket; // true
// OR (||): AT LEAST ONE must be true
boolean getsDiscount = (age < 12) || (age >= 65); // falseCommon Pitfalls
- Confusing the assignment operator (`=`) with the equality operator (`==`). One assigns a value, the other compares values.
- Integer division: `5 / 2` will give you `2`, not `2.5`. To get decimals, at least one number must be a `double` (e.g., `5.0 / 2`).
Interview Tips
- Interviewers love asking about 'Short-Circuit' evaluation. In `A && B`, if `A` is false, Java won't even bother checking `B` because the whole thing is already false! It saves time.
Real-World Example
Operators are used constantly in business logic, like determining if a user gets free shipping.
public class CartLogic {
public static void main(String[] args) {
double cartTotal = 45.0;
boolean hasPremiumMembership = true;
// You get free shipping if you spend over $50 OR have premium
boolean freeShipping = (cartTotal >= 50.0) || hasPremiumMembership;
System.out.println("Free Shipping? " + freeShipping);
}
}