Java Operators
4 min read ·
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
| Operator | Meaning |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus |
Example
Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1
Note
Division between two integers removes decimal part.
Assignment Operators
Assignment operators are used to assign values to variables.
| Operator | Example | Meaning |
|---|---|---|
| = | a = 5 | Assign |
| += | a += 3 | a = a + 3 |
| -= | a -= 2 | a = a - 2 |
| *= | a *= 4 | a = a * 4 |
| /= | a /= 2 | a = a / 2 |
| %= | a %= 3 | a = a % 3 |
Example
Output
15
30
Comparison Operators
Comparison operators are used to compare two values.
| Operator | Meaning |
|---|---|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than equal |
| <= | Less than equal |
Example
Output
false
true
true
false
Logical Operators
Logical operators are used with boolean values.
| Operator | Meaning | ||
|---|---|---|---|
| && | Logical AND | ||
| Logical OR | |||
| ! | Logical NOT |
Example
Output
Can Drive: true
Pro Tip
Logical AND returns true only if both conditions are true.
Increment and Decrement Operators
Used to increase or decrease value by 1.
| Operator | Meaning |
|---|---|
| ++ | Increment |
| -- | Decrement |
Example
Output
6
5
Pre and Post Increment Example
Output
6
6
7
Caution
Pre increment increases value first. Post increment uses value first then increases.
Ternary Operator
Used as a short form of if else.
Syntax
condition ? valueIfTrue : valueIfFalse
Example
Output
Pass
Real World Scenario
Ternary operator is commonly used in UI logic to display different messages based on conditions.
Exercise
- Write a program to check whether a number is even or odd using modulus operator.
- Create a program that checks if a person is eligible to vote.
- Use ternary operator to check whether a number is positive or negative.