operators
What Are Operators?
Operators are special symbols that perform operations on variables and values. Java groups operators into several categories: arithmetic, assignment, comparison, logical, and unary operators.
Arithmetic Operators
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 10 / 3 | 3 (integer division) |
% | Modulus (remainder) | 10 % 3 | 1 |
Important: When both operands are integers,/performs integer division and truncates the decimal part.10 / 3gives3, not3.33. To get a decimal result, make at least one operand adouble:10.0 / 3gives3.333....
Assignment Operators
int x = 10;
x += 5; // x = x + 5 -> 15
x -= 3; // x = x - 3 -> 12
x *= 2; // x = x * 2 -> 24
x /= 4; // x = x / 4 -> 6
x %= 4; // x = x % 4 -> 2Comparison (Relational) Operators
These always evaluate to a boolean — true or false.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | 5 == 5 → true |
!= | Not equal to | 5 != 3 → true |
> | Greater than | 5 > 3 → true |
< | Less than | 5 < 3 → false |
>= | Greater than or equal to | 5 >= 5 → true |
<= | Less than or equal to | 3 <= 5 → true |
Logical Operators
Used to combine multiple boolean expressions.
| Operator | Meaning | Example |
|---|---|---|
&& | AND — true only if both sides are true | (5 > 3) && (2 < 4) → true |
|| | OR — true if at least one side is true | (5 > 3) || (2 > 4) → true |
! | NOT — reverses the boolean value | !(5 > 3) → false |
Unary Operators
int a = 5;
a++; // post-increment, a becomes 6
a--; // post-decrement, a becomes 5 again
-a; // negation, gives -5
!true; // logical negation, gives false
Note:a++(post-increment) returns the original value before incrementing, while++a(pre-increment) increments first and then returns the new value. This distinction matters when used inline in expressions.
Operator Precedence
Just like in math, some operators are evaluated before others. Multiplication and division happen before addition and subtraction unless parentheses say otherwise:
int result = 2 + 3 * 4; // 14, not 20
int result2 = (2 + 3) * 4; // 20
Coming up next: Learn how to make decisions in your code using if-else statements and switch expressions.