☕ Java

Operators in Java

Operators are the symbols that tell Java what to do with your data — add it, compare it, flip it, combine it. You use operators in literally every line of real code, so getting comfortable with them early pays off immediately.

Arithmetic Operators — Math in Code

The basics — but with one important gotcha: integer division in Java truncates, it doesn't round. 10 / 3 gives you 3, not 3.33. If you want the decimal, make sure at least one operand is a double.
Java
int a = 10, b = 3;
System.out.println(a + b);   // 13  — addition
System.out.println(a - b);   // 7   — subtraction
System.out.println(a * b);   // 30  — multiplication
System.out.println(a / b);   // 3   — integer division (3.33... gets chopped to 3!)
System.out.println(a % b);   // 1   — modulus (remainder) — great for checking even/odd
System.out.println(a++);     // 10  — post-increment: uses current value, THEN increments
System.out.println(++a);     // 12  — pre-increment: increments FIRST, then uses value

// Fix integer division: cast to double first
System.out.println((double) a / b);  // 3.333...

Relational & Logical Operators — Decision Making

These operators produce a boolean (true/false) result. They're the backbone of every if statement, every loop condition, every filter.
Java
int x = 5, y = 10;

// Relational — comparing two values
System.out.println(x > y);   // false — is 5 greater than 10? No.
System.out.println(x < y);   // true
System.out.println(x == y);  // false — equality check (NOT assignment, that's =)
System.out.println(x != y);  // true  — not equal

// Logical — combining conditions
// Real use: "Is the user logged in AND is their account active?"
System.out.println(x < y && x > 0);   // true — both must be true (AND)
System.out.println(x > y || x > 0);   // true — at least one must be true (OR)
System.out.println(!(x > y));          // true — flips the result (NOT)

Ternary Operator — One-Line if/else

The ternary operator is a compact way to assign a value based on a condition. Perfect for simple yes/no decisions. Think of it as: "If this is true, give me this — otherwise give me that."
Java
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status);  // Adult

// Real-world usage: showing discount label
double cartTotal = 1500.0;
String discount = (cartTotal > 1000) ? "10% OFF applied" : "No discount";

// Nested ternary (use sparingly — readability drops fast)
int score = 72;
String grade = (score >= 90) ? "A" : (score >= 75) ? "B" : (score >= 60) ? "C" : "F";