Operators
TL;DR
Operators in Java are special symbols that perform specific operations on one, two, or three operands, and then return a result. The most common are Arithmetic (+, -, *, /, %), Relational (==, !=, <, >), and Logical (&&, ||, !).
Concept
Java groups operators into several categories based on their functionality:
- Arithmetic Operators: Perform mathematical operations (
+,-,*,/,%,++,--). - Assignment Operators: Assign values to variables (
=,+=,-=). - Relational (Comparison) Operators: Compare two values and return a boolean (
==,!=,>,<,>=,<=). - Logical Operators: Used to determine the logic between variables or values (
&&Logical AND,||Logical OR,!Logical NOT). - Bitwise Operators: Perform bit manipulation on integer types (
&,|,^,~,<<,>>,>>>). - Ternary Operator: A shorthand for an if-else statement (
condition ? exprIfTrue : exprIfFalse).
Examples
public class OperatorExample {
public static void main(String[] args) {
int a = 10, b = 5;
// Arithmetic
System.out.println("Modulo: " + (a % 3)); // Remainder is 1
// Post-increment vs Pre-increment
int x = 5;
System.out.println(x++); // Prints 5, then x becomes 6
System.out.println(++x); // x becomes 7, then prints 7
// Logical & Relational
if (a > b && b > 0) {
System.out.println("Both conditions are true!");
}
// Ternary
String result = (a % 2 == 0) ? "Even" : "Odd";
}
}
Interview Questions
Q: What is the difference between & and &&?
A: & is a bitwise AND operator (or logical AND that always evaluates both sides). && is the logical “short-circuit” AND. With &&, if the left side evaluates to false, the right side is never executed because the overall result is guaranteed to be false.
Q: What is the difference between >> and >>>?
A: >> is a signed right shift. It preserves the sign bit (fills the left with 0s if positive, 1s if negative). >>> is an unsigned right shift. It always fills the leftmost bits with 0s, regardless of the original sign.