Java operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. They are essential for manipulating variables and values in Java programs.
Arithmetic operators perform basic mathematical operations.
Example:
int a = 10, b = 3;
int sum = a + b; // 13
int difference = a - b; // 7
int product = a * b; // 30
int quotient = a / b; // 3
int remainder = a % b; // 1
Assignment operators are used to assign values to variables.
Example:
int x = 5;
x += 3; // x is now 8
x *= 2; // x is now 16
Comparison operators are used to compare two values.
Example:
int a = 5, b = 7;
boolean isEqual = (a == b); // false
boolean isGreater = (a > b); // false
Logical operators are used to determine the logic between variables or values.
Example:
boolean x = true, y = false;
boolean result = x && y; // false
result = x || y; // true
result = !x; // false
Bitwise operators perform operations on individual bits of integer types.
Example:
int a = 5, b = 3;
int result = a & b; // 1
result = a | b; // 7
result = a ^ b; // 6
result = ~a; // -6
result = a << 1; // 10
result = a >> 1; // 2
Java follows a specific order of precedence for operators. When multiple operators are used in an expression, those with higher precedence are evaluated first.
Precedence | Operator |
---|---|
1 | Postfix (expr++, expr--) |
2 | Unary (++expr, --expr, +expr, -expr, ~, !) |
3 | Multiplicative (*, /, %) |
4 | Additive (+, -) |
5 | Shift (<<, >>, >>>) |
6 | Relational (<, >, <=, >=, instanceof) |
7 | Equality (==, !=) |
8 | Bitwise AND (&) |
9 | Bitwise XOR (^) |
10 | Bitwise OR (|) |
11 | Logical AND (&&) |
12 | Logical OR (||) |
13 | Ternary (?:) |
14 | Assignment (=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=) |
Understanding Java operators is crucial for writing efficient and effective Java code. They form the foundation for manipulating data and controlling program flow in Java Classes and Objects. As you progress in your Java journey, you'll find these operators essential in various aspects of programming, from simple calculations to complex Java Conditional Statements and Java Loops.