Operators in Java
Introduction
Operators in Java are special symbols that perform specific operations on one, two, or three operands, and then return a result. They are the building blocks of expressions and logic in Java programs. Understanding operators, their precedence, and their associativity is critical for writing correct mathematical and logical expressions.
Categories of Operators
Java operators can be broadly classified into the following categories:
1. Arithmetic Operators
Used for performing standard mathematical operations.
+(Addition): Adds two operands.-(Subtraction): Subtracts second operand from the first.*(Multiplication): Multiplies both operands./(Division): Divides numerator by denominator.%(Modulus): Returns the remainder of a division.
int a = 10, b = 3;
System.out.println(a % b); // Output: 1
2. Unary Operators
Operate on a single operand.
+(Unary plus): Indicates a positive value.-(Unary minus): Negates an expression.++(Increment): Increases value by 1.--(Decrement): Decreases value by 1.!(Logical NOT): Inverts a boolean value.
Pre-increment vs. Post-increment:
int x = 5;
int y = ++x; // x becomes 6, then y becomes 6 (Pre)
int z = x++; // z becomes 6, then x becomes 7 (Post)
3. Assignment Operators
Used to assign values to variables.
=(Simple assignment)+=,-=,*=,/=,%=(Compound assignment)
int a = 5;
a += 3; // Equivalent to: a = a + 3 (a becomes 8)
Note: Compound assignment operators inherently cast the result to the target variable type.
4. Relational (Comparison) Operators
Determine the relationship between two operands. Return a boolean.
==(Equal to)!=(Not equal to)>(Greater than)<(Less than)>=(Greater than or equal to)<=(Less than or equal to)
5. Logical Operators
Used to combine multiple boolean expressions.
&&(Logical AND): Returns true if both conditions are true. Short-circuits if the first condition is false.||(Logical OR): Returns true if at least one condition is true. Short-circuits if the first condition is true.!(Logical NOT): Reverses the boolean state.
if (obj != null && obj.isValid()) {
// Safely operates because && short-circuits before throwing NullPointerException
}
6. Bitwise and Bit Shift Operators
Perform manipulation of individual bits of integer types.
&(Bitwise AND)|(Bitwise OR)^(Bitwise XOR)~(Bitwise Complement)<<(Left shift): Shifts bits left, filling with zeros (multiplies by 2).>>(Signed right shift): Shifts bits right, preserving the sign bit (divides by 2).>>>(Unsigned right shift): Shifts bits right, filling with zeros regardless of sign.
int a = 5; // 0101
int b = 3; // 0011
int result = a & b; // 0001 (Output: 1)
7. Ternary (Conditional) Operator
The only operator that takes three operands. A shorthand for an if-else statement.
Syntax: condition ? exprIfTrue : exprIfFalse
int age = 18;
String status = (age >= 18) ? "Adult" : "Minor";
8. Instanceof Operator
Tests whether an object is an instance of a specific class, subclass, or interface.
String s = "Hello";
boolean isString = s instanceof String; // true
Java 16 introduced pattern matching for instanceof, which implicitly casts the object.
Operator Precedence
Precedence dictates the order in which operators are evaluated in complex expressions. For example, multiplication has higher precedence than addition.
int result = 5 + 3 * 2; // result is 11, not 16
High to Low Precedence (Simplified):
- Postfix (
expr++,expr--) - Unary (
++expr,--expr,+,-,~,!) - Multiplicative (
*,/,%) - Additive (
+,-) - Shift (
<<,>>,>>>) - Relational (
<,>,<=,>=,instanceof) - Equality (
==,!=) - Bitwise (
&,^,|) - Logical AND (
&&) - Logical OR (
||) - Ternary (
? :) - Assignment (
=,+=, etc.)
When operators have the same precedence, associativity rules apply. Most operators evaluate left-to-right, but assignment and unary operators evaluate right-to-left. Use parentheses () to explicitly define evaluation order and improve code readability.