Operators
Arithmetic, relational, logical, bitwise operators
Interview Relevant: Operator precedence and behavior frequently tested
9 min read
What are Operators?
Operators are symbols that perform operations on variables and values. Java has multiple types of operators for different operations.
Arithmetic Operators
Used for mathematical calculations:
+(Addition),-(Subtraction),*(Multiplication)/(Division),%(Modulus - remainder)
Relational Operators
Used to compare values. Return boolean (true/false):
==(Equal),!=(Not equal)<(Less),>(Greater)<=(Less or equal),>=(Greater or equal)
Logical Operators
Used for boolean operations:
&&(AND - both must be true),||(OR - either can be true)!(NOT - reverses boolean value)
Assignment Operators
Used to assign values:
=(Assign),+=,-=,*=,/=
Increment/Decrement Operators
++(Increment),--(Decrement)- Pre-increment:
++x, Post-increment:x++
ā ļø Gotcha: ++x increments BEFORE returning, while x++ increments AFTER returning. This matters when used in expressions!
Code Examples
Arithmetic operators in action
java
1// Arithmetic operators
2int a = 10, b = 3;
3System.out.println(a + b); // 13
4System.out.println(a - b); // 7
5System.out.println(a * b); // 30
6System.out.println(a / b); // 3
7System.out.println(a % b); // 1Comparison operators return boolean values
java
1// Relational operators
2int x = 10, y = 20;
3System.out.println(x == y); // false
4System.out.println(x != y); // true
5System.out.println(x < y); // true
6System.out.println(x > y); // false
7System.out.println(x <= y); // true
8System.out.println(x >= y); // falseLogical operators for combining boolean conditions
java
1// Logical operators
2boolean p = true, q = false;
3System.out.println(p && q); // false (AND)
4System.out.println(p || q); // true (OR)
5System.out.println(!p); // false (NOT)
6
7// Practical use
8int age = 25;
9boolean isStudent = true;
10if (age >= 18 && isStudent) {
11 System.out.println("Student over 18");
12}The important difference between ++x and x++
java
1// Pre vs Post increment
2int x = 5;
3int y = ++x; // Pre-increment: x becomes 6, then y = 6
4System.out.println(x + ", " + y); // 6, 6
5
6int a = 5;
7int b = a++; // Post-increment: b = 5, then a becomes 6
8System.out.println(a + ", " + b); // 6, 5Use Cases
- Mathematical calculations and data manipulation
- Comparing values in conditional statements
- Combining multiple conditions with logical operators
- Updating variables with compound assignment operators
- Incrementing loop counters
- Building complex boolean expressions
Common Mistakes to Avoid
- Using = (assignment) instead of == (comparison)
- Confusing && (AND) with || (OR)
- Not understanding operator precedence
- Pre vs post increment behavior differences
- Integer division truncating results (10/3 = 3, not 3.33)
- Comparing objects with == instead of .equals()