- Understand different types of operators
- Learn arithmetic, comparison, and logical operators
- Master operator precedence
Operators in Java
Operators are the symbols that tell Java what to do with your data. Add numbers, compare values, check conditions—operators make it all happen.
Arithmetic operators — doing math
These work exactly like you'd expect from basic math:
| Operator | What it does | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 6 / 3 |
2 |
% |
Modulo (remainder) | 7 % 3 |
1 |
int total = 100;
int discount = 15;
int finalPrice = total - discount; // 85
int quantity = 3;
int price = 20;
int cost = quantity * price; // 60
Integer division — watch out for this
When you divide two integers, Java gives you an integer result (no decimals):
int result = 7 / 2; // gives 3, not 3.5
// To get decimals, make at least one value a double:
double correctResult = 7.0 / 2; // gives 3.5
The modulo operator (%) — finding remainders
The % operator gives you the remainder after division. Super useful for checking if numbers are even/odd or cycling through ranges:
int remainder = 17 % 5; // 2 (17 ÷ 5 = 3 remainder 2)
// Check if a number is even:
boolean isEven = (num % 2 == 0);
// Wrap around values (like hours on a clock):
int hour = 25 % 24; // 1 (hours wrap to 0-23)
Comparison operators — testing conditions
These compare two values and give you true or false:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
equals | 5 == 5 |
true |
!= |
not equals | 5 != 3 |
true |
> |
greater than | 5 > 3 |
true |
< |
less than | 5 < 3 |
false |
>= |
greater or equal | 5 >= 5 |
true |
<= |
less or equal | 3 <= 5 |
true |
int age = 18;
boolean canVote = age >= 18; // true
int score = 85;
boolean passed = score > 60; // true
Common mistake with Strings:
String a = "hello";
String b = "hello";
// Wrong way:
if (a == b) { ... } // compares references, not content
// Right way:
if (a.equals(b)) { ... } // compares actual content
Logical operators — combining conditions
Use these to combine multiple boolean expressions:
| Operator | Meaning | Example | Result |
|---|---|---|---|
&& |
AND (both must be true) | true && false |
false |
| ` | ` | OR (at least one true) | |
! |
NOT (flips the value) | !true |
false |
int age = 25;
boolean hasLicense = true;
// Can they rent a car? (need to be 21+ AND have license)
boolean canRent = (age >= 21) && hasLicense; // true
// Is entrance free? (kids under 5 OR seniors 65+)
boolean isFree = (age < 5) || (age >= 65); // false
Short-circuit evaluation
Java is smart—it stops checking as soon as it knows the answer:
// If age < 18 is false, Java never checks hasPermission
if (age < 18 && hasPermission) { ... }
// If isAdmin is true, Java doesn't bother checking isOwner
if (isAdmin || isOwner) { ... }
This matters when the second condition might cause an error:
// Safe: if list is null, the second check never runs
if (list != null && list.size() > 0) { ... }
Assignment operators — shortcuts for updating values
The basic assignment is =, but Java has shortcuts for common patterns:
| Operator | Long form | Short form |
|---|---|---|
+= |
x = x + 5 |
x += 5 |
-= |
x = x - 5 |
x -= 5 |
*= |
x = x * 2 |
x *= 2 |
/= |
x = x / 2 |
x /= 2 |
%= |
x = x % 3 |
x %= 3 |
int score = 100;
score += 50; // score is now 150
score *= 2; // score is now 300
score -= 100; // score is now 200
Increment and decrement — adding or subtracting 1
Special operators for the very common "add 1" or "subtract 1" operations:
int count = 5;
count++; // count is now 6 (same as count = count + 1)
count--; // count is now 5 (same as count = count - 1)
Pre-increment vs post-increment
The placement of ++ and -- matters when you use them in expressions:
int x = 5;
int y = x++; // y = 5, then x becomes 6 (post-increment)
int a = 5;
int b = ++a; // a becomes 6, then b = 6 (pre-increment)
Most of the time, use them on their own line to avoid confusion:
count++; // clear and simple
The ternary operator — shorthand if/else
A compact way to pick one of two values based on a condition:
condition ? valueIfTrue : valueIfFalse
int age = 20;
String category = (age >= 18) ? "adult" : "minor"; // "adult"
int a = 5, b = 10;
int max = (a > b) ? a : b; // 10
Compare to the longer if/else version:
// Same thing, more verbose:
String category;
if (age >= 18) {
category = "adult";
} else {
category = "minor";
}
Use the ternary operator for simple assignments. If the logic gets complex, stick with regular if/else for readability.
Operator precedence — what happens first
When you have multiple operators, Java follows precedence rules (like PEMDAS in math):
int result = 5 + 3 * 2; // result = 11, not 16
// Multiplication happens first: 5 + (3 * 2)
Precedence order (high to low):
- Parentheses
() - Unary
++,--,!,- - Multiplication/Division
*,/,% - Addition/Subtraction
+,- - Comparison
<,>,<=,>= - Equality
==,!= - Logical AND
&& - Logical OR
|| - Ternary
? : - Assignment
=,+=,-=, etc.
Best practice: use parentheses to make your intent clear:
// Unclear:
int x = a + b * c / d - e;
// Clear:
int x = a + ((b * c) / d) - e;
Common pitfalls and how to avoid them
1. Confusing = with ==
int x = 5;
// Wrong: assignment, not comparison
if (x = 10) { ... } // compile error (if expects boolean)
// Right: comparison
if (x == 10) { ... }
2. Forgetting parentheses in complex conditions
// Wrong: && has higher precedence than ||
if (age < 13 || age > 19 && hasPermission) { ... }
// Right: make it explicit
if ((age < 13) || (age > 19 && hasPermission)) { ... }
3. Integer division when you want decimals
double average = sum / count; // wrong if sum and count are ints
double average = (double) sum / count; // correct
Practical examples
Calculate discount price:
double price = 100.0;
double discount = 0.15; // 15%
double finalPrice = price * (1 - discount); // 85.0
Check if a year is a leap year:
int year = 2024;
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
Swap two variables:
int a = 5, b = 10;
int temp = a;
a = b;
b = temp;
// Now a = 10, b = 5
Clamp a value to a range:
int value = 150;
int min = 0, max = 100;
int clamped = (value < min) ? min : (value > max) ? max : value; // 100
What to remember
- Use arithmetic operators for math:
+,-,*,/,% - Compare values with
==,!=,>,<,>=,<= - Combine conditions with
&&(AND),||(OR),!(NOT) - Shortcuts exist:
+=,-=,++,-- - Integer division drops decimals:
7 / 2gives3 - Use
.equals()for String comparison, not== - Parentheses clarify precedence and make code readable
Master these operators and you can build any calculation or condition your program needs.
