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 are used to perform mathematical operations.
int a = 10, b = 3;
int c = a + b;
int d = a - b;
int e = a * b;
float f = a / b; // f will be 3.33 (float as int division results in int)
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 are used to assign values to variables.
int a = 10;
Simple Assignment (=)
int b = a; // b also becomes 10
Additive Assignment (+=)
a += b; // a becomes 20
Subtractive Assignment (-=)
a -= b; // a becomes 10 again
Multiplicative Assignment (*=)
a *= b; // a becomes 30
Divisive Assignment (/=)
a /= b; // a becomes 3
Modulus Assignment (%=)
a %= b; // a becomes 1
Comparison operators compare two operands and determine their relation.
Equal to (==)
(a == b) // Returns false as a and b are not equal
Not equal to (!=)
(a != b) // Returns true
Greater than (>)
(a > b) // Returns true
Less than (<)
(a < b) // Returns false
Greater than or equal to (>=)
(a >= b) // Returns true
Less than or equal to (<=)
(a <= b) // Returns false
Logical operators combine two or more conditions (boolean expressions).
(a > b) && (c < d) evaluates to true if both conditions are true
(a > b) || (c < d) evaluates to true if any condition is true
!(a < b) inverts the result, returning false if the condition is true.
Bitwise operators perform operations on bits and bit patterns of operands.
int result = (a & b); // Performs bitwise AND
int result = (a | b); // Performs bitwise OR
int result = (a ^ b); // Performs bitwise XOR
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
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.