Java Operators
1. Arithmetic Operators:
// Addition
int sum = 5 + 3; // Result: 8
// Subtraction
int difference = 7 - 4; // Result: 3
// Multiplication
int product = 2 * 6; // Result: 12
// Division
int quotient = 10 / 2; // Result: 5
// Modulus
int remainder = 15 % 4; // Result: 3
2. Relational Operators:
// Equal to
boolean isEqual = (5 == 5); // Result: true
// Not equal to
boolean isNotEqual = (4 != 3); // Result: true
// Greater than
boolean isGreater = (7 > 5); // Result: true
// Less than
boolean isLess = (2 < 4); // Result: true
// Greater than or equal to
boolean isGreaterOrEqual = (10 >= 8); // Result: true
// Less than or equal to
boolean isLessOrEqual = (6 <= 9); // Result: true
3. Logical Operators:
// Logical AND
boolean resultAnd = condition1 && condition2; // Result: false
// Logical OR
boolean resultOr = condition1 || condition2; // Result: true
// Logical NOT
boolean resultNot = !condition1; // Result: false
4. Assignment Operators:
// Assignment
int x = 10;
// Compound Assignment
int a = 5;
a += 3; // Equivalent to: a = a + 3;
5. Bitwise Operators:
Bitwise operators perform operations at the bit level.
// Bitwise AND (&)
// Bitwise OR (|)
// Bitwise XOR (^)
// Bitwise NOT (~)
// Left Shift (<<)
// Right Shift (>>)
// Zero-fill Right Shift (>>>)
6. Other Operators:
// Conditional (Ternary) Operator (? :)
int max = (a > b) ? a : b;
// Instanceof Operator
if (obj instanceof MyClass) {
// code
}
These are some of the main categories of operators in Java. Understanding how to use operators is essential for writing effective and expressive Java code.