#5 Known is a Drop! Operators in JAVA
Source: Dev.to
Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.
Simple Assignment Operator
= Simple assignment operator
Arithmetic Operators
| Operator | Description |
|---|---|
+ | Additive operator (also used for String concatenation) |
- | Subtraction operator |
* | Multiplication operator |
/ | Division operator |
% | Remainder operator |
Unary Operators
// Unary plus operator; indicates a positive value (numbers are positive without this)
int a = +5;
// Unary minus operator; negates an expression
int b = -a;
++Increment operator; increments a value by 1--Decrement operator; decrements a value by 1!Logical complement operator; inverts the value of a boolean
Equality and Relational Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
>= | Greater than or equal to |
> | Signed right shift |
>>> | Unsigned right shift |
& | Bitwise AND |
^ | Bitwise exclusive OR |
| ` | ` |
Compound Assignments
You can combine arithmetic operators with the simple assignment operator to create compound assignments.
x += 1; // equivalent to x = x + 1
x -= 2; // equivalent to x = x - 2
x *= 3; // equivalent to x = x * 3
x /= 4; // equivalent to x = x / 4
x %= 5; // equivalent to x = x % 5
Operator Precedence
Consider the expression:
(4 * 4) + (8 * 8) * (4 * 4) - 16 / 4
- Parentheses have the highest precedence.
- Evaluate multiplicative operators (
*,/) from left to right. - Evaluate additive operators (
+,-) from left to right.
Step‑by‑step evaluation
// After evaluating parentheses
16 + (8 * 8) * (4 * 4) - 16 / 4
16 + 64 * (4 * 4) - 16 / 4
16 + 64 * 16 - 16 / 4
// Multiplicative operators
16 + 1024 - 16 / 4
16 + 1024 - 4
// Additive operators
1040 - 4
1036
Example with Unary Operators
int i = 10;
int n = i++ % 5; // n = 0 (10 % 5); i becomes 11
int j = 10;
int m = ++j % 5; // j becomes 11; m = 1 (11 % 5)
The final result of the original expression is 1036, which can now be used or assigned to a variable.