GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR

➕ Lesson 4: Java Operators

⏱️ Estimated time: 20 minutes | Difficulty: Beginner

Logic and Math

Java operators are special symbols used to perform operations on variables and values.

Arithmetic Operators

int a = 10, b = 3;
a + b   // 13  Addition
a - b   // 7   Subtraction
a * b   // 30  Multiplication
a / b   // 3   Integer division (truncates!)
a % b   // 1   Modulus (remainder)

// Watch out for integer division!
10 / 3     // 3 (not 3.333!)
10.0 / 3   // 3.333... (use double for decimal)

// Increment / Decrement
int x = 5;
x++;  // x is now 6
x--;  // x is now 5
x += 10;  // x is now 15

Comparison Operators

==   // Equal to
!=   // Not equal to
>    // Greater than
<    // Less than
>=   // Greater than or equal
<=   // Less than or equal

// Examples
5 == 5   // true
5 != 3   // true
10 > 5   // true

Logical Operators

&&   // AND — both must be true
||   // OR  — at least one true
!    // NOT — reverses boolean

int age = 25;
boolean hasID = true;
boolean canDrink = (age >= 21) && hasID;  // true

// Ternary operator (shorthand if/else)
String msg = (age >= 18) ? "Adult" : "Minor";  // "Adult"

Math Class

Math.max(10, 20);    // 20
Math.min(10, 20);    // 10
Math.abs(-5);        // 5
Math.sqrt(16);       // 4.0
Math.pow(2, 3);      // 8.0
Math.round(3.7);     // 4
Math.random();       // Random 0.0 to 1.0

✅ Quick Quiz

❓ What is 10 / 3 in Java (both ints)?

❓ What does && mean?

❓ What does the ternary operator do?

← Previous Next: Control Flow →