Operators are special symbols that perform operations on variables and values. Java provides a rich set of operators.
Arithmetic operators are used to perform common mathematical operations.
| Operator | Name | Description | Example |
|---|---|---|---|
+ |
Addition | Adds together two values | x + y |
- |
Subtraction | Subtracts one value from another | x - y |
* |
Multiplication | Multiplies two values | x * y |
/ |
Division | Divides one value by another | x / y |
% |
Modulus | Returns the division remainder | x % y |
++ |
Increment | Increases the value of a variable by 1 | x++ |
-- |
Decrement | Decreases the value of a variable by 1 | x-- |
int x = 10;
int y = 3;
System.out.println("Remainder: " + (x % y)); // Outputs 1
x++;
System.out.println("Incremented x: " + x); // Outputs 11
Assignment operators are used to assign values to variables.
| Operator | Example | Same As |
|---|---|---|
= |
x = 5 |
x = 5 |
+= |
x += 3 |
x = x + 3 |
-= |
x -= 3 |
x = x - 3 |
*= |
x *= 3 |
x = x * 3 |
/= |
x /= 3 |
x = x / 3 |
%= |
x %= 3 |
x = x % 3 |
Comparison operators are used to compare two values and return a boolean value (true or false).
| Operator | Name | Example |
|---|---|---|
== |
Equal to | x == y |
!= |
Not equal | x != y |
> |
Greater than | x > y |
< |
Less than | x < y |
>= |
Greater than or equal to | x >= y |
<= |
Less than or equal to | x <= y |
int x = 10; int y = 20; System.out.println(x > y); // Outputs false
Logical operators are used to determine the logic between variables or values.
| Operator | Name | Description | Example |
|---|---|---|---|
&& |
Logical And | Returns true if both statements are true |
x < 5 && x < 10 |
| ` | ` | Logical Or | |
! |
Logical Not | Reverses the result, returns false if the result is true |
!(x < 5 && x < 10) |
int x = 7; System.out.println(x > 5 && x < 10); // Both are true, so it outputs true