Learn Java Operators and Math

Operators and Math

⏱ 15 min read
Operators are symbols that perform operations on variables and values.

Arithmetic Operators:
+ (addition), - (subtraction), * (multiplication), / (division), % (modulus/remainder)

IMPORTANT: In Java, dividing two integers always gives an integer.
10 / 3 = 3 (not 3.333!)
To get the decimal result, cast one number to double first:
(double)10 / 3 = 3.333

Shorthand Assignment Operators:
x += 5 → same as x = x + 5
x -= 3 → same as x = x - 3
x *= 2 → same as x = x * 2
x /= 4 → same as x = x / 4
x++ → adds 1 to x
x-- → subtracts 1 from x

Comparison Operators (always return true or false):
== (equal to), != (not equal), < (less than), > (greater than), <= (less or equal), >= (greater or equal)

Logical Operators:
&& (AND) — both conditions must be true
|| (OR) — at least one condition must be true
! (NOT) — flips true to false, or false to true

The Math Class:
Math.abs(-42) → 42
Math.max(10, 20) → 20
Math.min(10, 20) → 10
Math.pow(2, 10) → 1024.0
Math.sqrt(144) → 12.0
Math.round(3.7) → 4
Math.random() → random number between 0.0 and 1.0

To get a random dice roll (1 to 6):
int dice = (int)(Math.random() * 6) + 1;
Code Example
public class Operators {

    public static void main(String[] args) {
        int a = 10, b = 3;

        // Arithmetic
        System.out.println(a + b);          // 13
        System.out.println(a - b);          // 7
        System.out.println(a * b);          // 30
        System.out.println(a / b);          // 3 — integer division!
        System.out.println(a % b);          // 1 — remainder
        System.out.println((double) a / b); // 3.3333...

        // Shorthand
        int x = 10;
        x += 5; x -= 3; x *= 2; x /= 4;
        System.out.println(x); // 6

        // Comparison
        System.out.println(a == b); // false
        System.out.println(a != b); // true
        System.out.println(a < b);  // false

        // Logical
        boolean isAdult = true;
        boolean hasTicket = false;
        System.out.println(isAdult && hasTicket); // false
        System.out.println(isAdult || hasTicket); // true
        System.out.println(!isAdult);             // false

        // Math class
        System.out.println(Math.max(10, 20));  // 20
        System.out.println(Math.pow(2, 10));   // 1024.0
        System.out.println(Math.sqrt(144));    // 12.0

        // Random dice roll 1–6
        int dice = (int)(Math.random() * 6) + 1;
        System.out.println("Dice: " + dice);
    }

}
← Java: Variables and Types If Statements and Conditionals →

Log in to track your progress and earn badges as you complete lessons.

Log In to Track Progress