Lesson 4 of 25

Operators

Arithmetic and Assignment Operators

Java supports standard arithmetic operations and shorthand assignment operators.

Example
// Arithmetic
int sum = 10 + 3;     // 13
int diff = 10 - 3;    // 7
int prod = 10 * 3;    // 30
int quot = 10 / 3;    // 3 (integer division)
int rem = 10 % 3;     // 1 (modulus)

// Assignment shortcuts
int x = 10;
x += 5;   // x = 15
x -= 3;   // x = 12
x *= 2;   // x = 24
x /= 4;   // x = 6

// Increment/Decrement
x++;      // x = 7
x--;      // x = 6

Comparison and Logical Operators

Comparison operators return boolean values. Logical operators combine boolean expressions.

Example
// Comparison
boolean a = 5 > 3;    // true
boolean b = 5 == 5;   // true
boolean c = 5 != 3;   // true
boolean d = 5 >= 5;   // true

// Logical operators
boolean and = true && false;  // false
boolean or = true || false;   // true
boolean not = !true;          // false

// String comparison (use .equals(), NOT ==)
String s1 = "hello";
String s2 = "hello";
boolean eq = s1.equals(s2);   // true
boolean ci = s1.equalsIgnoreCase("HELLO"); // true

// Ternary operator
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";