Operators
Operators let you perform calculations, compare values, and combine conditions. Java groups them into a few categories: arithmetic, assignment, comparison, logical, and increment/decrement.
Arithmetic Operators
These perform basic math on numeric values.
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | 5 + 2 is 7 |
- | Subtraction | 5 - 2 is 3 |
* | Multiplication | 5 * 2 is 10 |
/ | Division | 5 / 2 is 2 (integer division) |
% | Modulus (remainder) | 5 % 2 is 1 |
int a = 10, b = 3;
System.out.println(a % b); // 1
int values with / discards the decimal part. 5 / 2 gives 2, not 2.5. Make at least one operand a double if you need a decimal result.Assignment Operators
Beyond the plain =, Java offers compound assignment operators that combine an operation with assignment:
| Operator | Equivalent to |
|---|---|
+= | x = x + value |
-= | x = x - value |
*= | x = x * value |
/= | x = x / value |
int total = 10;
total += 5; // total is now 15
Comparison (Relational) Operators
These compare two values and produce a boolean result (true or false).
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
int age = 20;
System.out.println(age >= 18); // true
Logical Operators
These combine or invert boolean expressions.
| Operator | Meaning |
|---|---|
&& | Logical AND — true only if both sides are true |
|| | Logical OR — true if at least one side is true |
! | Logical NOT — flips true to false and vice versa |
boolean hasTicket = true;
boolean isAdult = false;
System.out.println(hasTicket && isAdult); // false
Increment and Decrement Operators
++ and -- add or subtract 1 from a variable. Where you place them matters: as a
prefix (++x) the value changes before it's used; as a postfix
(x++) the value is used first, then changed.
int x = 5;
System.out.println(x++); // prints 5, then x becomes 6
System.out.println(x); // prints 6
int y = 5;
System.out.println(++y); // y becomes 6 first, then prints 6
Operator Precedence
When an expression has multiple operators, precedence decides which one Java evaluates first. Here's a short reference, from highest to lowest priority:
| Priority | Operators |
|---|---|
| 1 (highest) | ++ -- (unary) |
| 2 | * / % |
| 3 | + - |
| 4 | < <= > >= |
| 5 | == != |
| 6 | && |
| 7 | || |
| 8 (lowest) | = += -= *= /= |
() to make the intended order explicit — it costs nothing and makes your code easier for others to read.