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;
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;
Log in to track your progress and earn badges as you complete lessons.
Log In to Track Progress