Operators are symbols that perform operations on variables and values known as operands. Java provides a variety of operators for performing mathematical, logical, conditional, and assignment operations.
Mathematical Operators
Mathematical operators are used to perform mathematical operations.
int a = 10, b = 3;
Addition (+)
int c = a + b;
Subtraction (-)
int d = a - b;
Multiplication (*)
int e = a * b;
Division (/)
float f = a / b; // f will be 3.33 (float as int division results in int)
Modulus (%)
int g = a % b; // g will be 1 (remainder after dividing a by b)
Increment (++) and Decrement (--)
a++; // a becomes 11 a--; // a becomes 10 again
Assignment Operators
Assignment operators are used to assign values to variables.
int a = 10;
Simple Assignment (=)
int b = a; // b also becomes 10Additive Assignment (+=)
a += b; // a becomes 20Subtractive Assignment (-=)
a -= b; // a becomes 10 againMultiplicative Assignment (*=)
a *= b; // a becomes 30Divisive Assignment (/=)
a /= b; // a becomes 3Modulus Assignment (%=)
a %= b; // a becomes 1
Comparison Operators
Comparison operators compare two operands and determine their relation.
Equal to (==)
(a == b) // Returns false as a and b are not equalNot equal to (!=)
(a != b) // Returns trueGreater than (>)
(a > b) // Returns trueLess than (<)
(a < b) // Returns falseGreater than or equal to (>=)
(a >= b) // Returns trueLess than or equal to (<=)
(a <= b) // Returns false
Logical Operators
Logical operators combine two or more conditions (boolean expressions).
AND (&&)
(a > b) && (c < d) evaluates to true if both conditions are trueOR (||)
(a > b) || (c < d) evaluates to true if any condition is trueNOT (!)
!(a < b) inverts the result, returning false if the condition is true.
Bitwise Operators
Bitwise operators perform operations on bits and bit patterns of operands.
AND (&)
int result = (a & b); // Performs bitwise AND
OR (|)
int result = (a | b); // Performs bitwise OR
XOR (^)
int result = (a ^ b); // Performs bitwise XOR
NOT (~)
int result = ~a; // Performs bitwise complement
Left Shift (<<)
a << 2; // Shifts a by two bits toward left
Right Shift (>>)
a >> 2; // Shifts a by two bits toward right
Zero fill Right Shift (>>>)
a >>> 2; // Shifts with zero fill instead of preserving sign bit
Conditional Operator
int result = (condition)? True: False;
int max = (a > b) ? a : b; // Returns the larger of the two values
To conclude, operators are an essential part of any programming language. Understanding which operators to use and when helps improve the expressiveness and performance of your Java code. Using operators effectively can also make your code more concise and reduce complexity.