In Java, operators are symbols that perform operations on variables and values. Here are some of the commonly used operators in Java:
1. **Arithmetic Operators:**
- Used to perform mathematical operations.
- `+` (Addition), `-` (Subtraction), `*` (Multiplication), `/` (Division), `%` (Modulus)
Example:
```java
int a = 10, b = 20;
int sum = a + b; // 30
int difference = a - b; // -10
int product = a * b; // 200
int quotient = b / a; // 2
int remainder = b % a; // 0
```
2. **Comparison (Relational) Operators:**
- Used to compare two values.
- `==` (Equal to), `!=` (Not equal to), `>` (Greater than), `<` (Less than), `>=` (Greater than or equal to), `<=` (Less than or equal to)
Example:
```java
int x = 5, y = 10;
boolean isEqual = (x == y); // false
boolean isNotEqual = (x != y); // true
boolean isGreaterThan = (x > y); // false
```
3. **Logical Operators:**
- Used to perform logical operations.
- `&&` (Logical AND), `||` (Logical OR), `!` (Logical NOT)
Example:
```java
boolean condition1 = true, condition2 = false;
boolean resultAnd = (condition1 && condition2); // false
boolean resultOr = (condition1 || condition2); // true
boolean resultNot = !condition1; // false
```
4. **Assignment Operators:**
- Used to assign values to variables.
- `=` (Assignment), `+=` (Add and assign), `-=` (Subtract and assign), `*=` (Multiply and assign), `/=` (Divide and assign), `%=` (Modulus and assign)
Example:
```java
int num = 5;
num += 3; // num is now 8 (5 + 3)
num -= 2; // num is now 6 (8 - 2)
```
5. **Increment and Decrement Operators:**
- Used to increase or decrease the value of a variable by 1.
- `++` (Increment), `--` (Decrement)
Example:
```java
int count = 10;
count++; // count is now 11
count--; // count is now 10
```
6. **Conditional (Ternary) Operator:**
- Provides a concise way to implement a simple if-else statement.
- `? :` (Conditional Operator)
Example:
```java
int a = 5, b = 10;
int max = (a > b) ? a : b; // max is 10
```
These are some of the fundamental operators in Java. Understanding how to use them is crucial for writing effective and expressive code.
No comments:
Post a Comment