Java Operators
Java Operators Interview with follow-up questions
1. What are the different types of operators available in Java?
Java's operators by category:
- Arithmetic —
+ - * / %(+also concatenates strings). - Relational/comparison —
== != < > <= >=→boolean. - Logical —
&& || !(short-circuiting). - Bitwise & shift —
& | ^ ~,<< >> >>>(on integer types). - Assignment —
=plus compound+= -= *= /= %= &=etc. - Unary —
+ - ++ -- !. - Ternary/conditional —
cond ? a : b. - Type/other —
instanceof(with pattern binding since Java 16),new,.(member access),[], and the lambda/method-reference->/::.
boolean ok = (n > 0) && (n % 2 == 0);
if (obj instanceof String s && !s.isBlank()) use(s); // pattern + guard
The gotchas interviewers want surfaced: == compares object references, not contents — use .equals() for value equality; integer / truncates (7/2 == 2); >> is signed (arithmetic) shift while >>> is unsigned (logical) shift; and &&/|| short-circuit while &/| on booleans evaluate both sides.
A current note: Java has no === (that's JavaScript), and instanceof now supports pattern matching, which combines the type check and cast — modern code uses it instead of the old check-then-cast idiom.
Follow-up 1
Can you explain the difference between unary and binary operators?
Unary operators are operators that operate on a single operand, while binary operators are operators that operate on two operands. Unary operators include operators such as ++ (increment), -- (decrement), ! (logical NOT), and - (negation). Binary operators include operators such as + (addition), - (subtraction), * (multiplication), / (division), and % (modulus).
Follow-up 2
What is the use of ternary operator?
The ternary operator, also known as the conditional operator, is a shorthand way of writing if-else statements. It takes three operands: a condition, a value to be returned if the condition is true, and a value to be returned if the condition is false. The syntax of the ternary operator is as follows:
condition ? value_if_true : value_if_false
For example:
int x = 10;
int y = (x > 5) ? 1 : 0;
System.out.println(y); // Output: 1
Follow-up 3
How does the assignment operator work in Java?
The assignment operator (=) is used to assign a value to a variable. It works by evaluating the expression on the right-hand side of the operator and assigning the result to the variable on the left-hand side. For example:
int x = 10;
int y = 5;
x = y;
System.out.println(x); // Output: 5
```In this example, the value of y (which is 5) is assigned to the variable x.
2. How does the precedence of operators work in Java?
Operator precedence defines which operators bind tighter and therefore evaluate first in an expression; associativity breaks ties between operators of equal precedence (left-to-right for most binary operators; right-to-left for assignment and unary).
A rough high-to-low ordering: postfix ++ -- → unary + - ! ~ → multiplicative * / % → additive + - → shifts << >> >>> → relational < > instanceof → equality == != → bitwise & ^ | → logical && || → ternary ?: → assignment =.
int r = a + b * c; // b*c first, then + a
boolean x = a == b || c; // ? precedence: == before || → (a==b) || c
int v = 2 + 3 << 1; // + before << → (5) << 1 == 10 (surprising!)
The practical advice interviewers reward: don't memorize the full table — use parentheses to make intent explicit, especially when mixing arithmetic with bitwise/shift operators (whose low precedence trips people up) or comparisons with &&/||. Clear, parenthesized expressions are more maintainable and avoid subtle bugs. Also remember = is right-associative (a = b = c assigns c to b then b to a), and &&/|| short-circuit, which affects whether side-effects on the right run at all.
Follow-up 1
Can you give an example where operator precedence plays a crucial role?
Sure! Consider the expression a + b * c - d. If we didn't consider operator precedence, the expression would be evaluated from left to right, resulting in ((a + b) * c) - d. However, due to operator precedence, the multiplication operator * has higher precedence than the addition and subtraction operators. Therefore, the expression is actually evaluated as (a + (b * c)) - d. This can lead to different results depending on the values of a, b, c, and d.
Follow-up 2
How can we change the precedence of operators?
In Java, the precedence of operators cannot be changed. It is predefined and fixed. However, we can use parentheses to explicitly specify the order of evaluation in an expression. By using parentheses, we can override the default precedence and ensure that certain operations are performed before others.
For example, in the expression (a + b) * c, the addition operator + is evaluated first due to the parentheses, and then the result is multiplied by c.
Follow-up 3
What is the default precedence order of Java operators?
The default precedence order of Java operators, from highest to lowest, is as follows:
- Postfix operators:
expr++,expr-- - Unary operators:
++expr,--expr,+expr,-expr,~expr,!expr - Multiplicative operators:
*,/,% - Additive operators:
+,- - Shift operators:
<<,>>,>>> - Relational operators:
<,>,<=,>=,instanceof - Equality operators:
==,!= - Bitwise AND operator:
& - Bitwise exclusive OR operator:
^ - Bitwise inclusive OR operator:
| - Logical AND operator:
&& - Logical OR operator:
|| - Ternary conditional operator:
? : - Assignment operators:
=,+=,-=,*=,/=,%=,&=,^=,|=,<<=,>>=,>>>=
It is important to note that this is just the default precedence order, and it can be overridden by using parentheses to explicitly specify the order of evaluation.
3. What is the difference between '==' and '===' operators in Java?
This is a bit of a trick question: Java has no === operator — that's JavaScript's strict-equality operator. In Java the relevant comparison is == vs .equals():
==— compares identity: for primitives it compares values; for objects it compares references (whether they point to the same object)..equals()— compares logical/value equality as defined by the class (e.g.String, wrapper types, records compare contents).
String a = new String("hi");
String b = new String("hi");
a == b; // false — different objects
a.equals(b); // true — same characters
The classic gotchas interviewers are really testing:
- Always use
.equals()for objects (especiallyString); using==on strings is a top beginner bug. Integercaching: autoboxed values from -128 to 127 are cached, soInteger x = 100; Integer y = 100; x == yistrue, but at200it'sfalse— never compare wrappers with==.- For your own classes, override
equals()andhashCode()together (records do this automatically).
So the correct framing: "Java doesn't have ===; the real distinction is == (reference/identity) vs .equals() (value equality)."
Follow-up 1
Can you give a scenario where '==' and '===' would give different results?
Since the '=' operator is not available in Java, there is no scenario where '' and '===' would give different results in Java.
Follow-up 2
What is the importance of '===' operator?
The '===' operator in JavaScript is important because it not only checks if the values of the two operands are equal, but also checks if the operands are of the same type. This ensures strict equality comparison, which can be useful in certain scenarios where type coercion is not desired.
Follow-up 3
Is '===' operator available in Java like JavaScript?
No, the '===' operator is not available in Java. It is a strict equality operator specific to JavaScript.
4. Can you explain the concept of bitwise operators in Java?
Bitwise operators manipulate the individual bits of integer types (int, long, etc.), working at the binary level:
&AND — 1 only if both bits are 1.|OR — 1 if either bit is 1.^XOR — 1 if the bits differ.~NOT — inverts every bit (one's complement).<<left shift — shifts bits left (×2 per shift).>>signed right shift — shifts right, preserving the sign bit (÷2).>>>unsigned right shift — shifts right, filling with zeros (no sign extension).
int flags = 0;
flags |= 0b0100; // set a bit
boolean set = (flags & 0b0100) != 0; // test a bit
flags &= ~0b0100; // clear a bit
The source missed >>> — Java has three shift operators, and the unsigned >>> is a common interview point (it's why -1 >>> 28 gives a small positive number).
Uses interviewers like: flags/bitmasks, low-level protocols, hashing, and performance tricks (x << 1 for ×2, x & 1 for odd/even). A practical note: for boolean flag sets, modern Java favors EnumSet (clean and type-safe) over manual bit-twiddling, and Integer.bitCount/highestOneBit etc. cover common bit operations — but understanding the raw operators is still expected.
Follow-up 1
What are the different types of bitwise operators?
There are six bitwise operators in Java:
AND (&): Performs a bitwise AND operation on the corresponding bits of the operands.
OR (|): Performs a bitwise OR operation on the corresponding bits of the operands.
XOR (^): Performs a bitwise XOR (exclusive OR) operation on the corresponding bits of the operands.
NOT (~): Flips the bits of the operand, resulting in the one's complement.
Left Shift (<<): Shifts the bits of the left operand to the left by a specified number of positions, filling the rightmost positions with zeros.
Right Shift (>>): Shifts the bits of the left operand to the right by a specified number of positions, filling the leftmost positions with the sign bit (for signed values) or with zeros (for unsigned values).
Follow-up 2
Can you give a practical example where bitwise operators can be used?
Sure! One practical example where bitwise operators can be used is in the manipulation of individual bits in a byte or an integer. For example, let's say we have a byte value representing the status of multiple flags, and we want to check if a specific flag is set. We can use the bitwise AND operator to perform this check. Here's an example:
byte flags = 0b00101011;
byte flagToCheck = 0b00001000;
if ((flags & flagToCheck) != 0) {
System.out.println("Flag is set!");
} else {
System.out.println("Flag is not set!");
}```
In this example, the bitwise AND operator is used to check if the flagToCheck is set in the flags byte. If the result of the bitwise AND operation is not zero, it means the flag is set.
Follow-up 3
What is the difference between bitwise and logical operators?
The main difference between bitwise and logical operators is the level at which they operate. Bitwise operators work at the binary level, manipulating individual bits of the operands. Logical operators, on the other hand, work at the boolean level, operating on boolean expressions and producing boolean results.
Bitwise operators perform operations on each bit of the operands, whereas logical operators perform operations on the entire boolean expressions. Bitwise operators are commonly used for low-level bit manipulation and optimization, while logical operators are used for boolean logic and control flow.
Another difference is the short-circuit behavior. Logical operators have short-circuit behavior, meaning that the second operand is not evaluated if the result can be determined by the first operand. Bitwise operators do not have short-circuit behavior and always evaluate both operands.
5. What is the role of relational operators in Java?
Relational (comparison) operators compare two operands and produce a boolean (true/false), driving conditions in if, loops, and the ternary operator. The six:
==equal to,!=not equal to>greater than,<less than>=greater-or-equal,<=less-or-equal
if (age >= 18) allow();
boolean done = (count == limit);
The critical gotcha interviewers always probe: the ordering operators (< > <= >=) work on primitive numeric types (and char), but ==/!= on objects compare references, not contents — so == on two Strings or Integers is almost always a bug; use .equals() for value equality, or Comparable.compareTo()/Comparator for ordering objects.
Two more current notes: comparing floating-point values with == is unreliable (use a tolerance/epsilon, or Double.compare); and to order custom objects you implement Comparable (natural order) or pass a Comparator (e.g. Comparator.comparing(User::age)), since </> don't work on reference types. So relational operators are for primitives/conditions, and value/ordering comparison of objects uses equals/compareTo.
Follow-up 1
Can you give an example of each relational operator?
Sure! Here are examples of each relational operator in Java:
==(equal to):
int a = 5;
int b = 5;
boolean result = (a == b);
// result will be true
!=(not equal to):
int a = 5;
int b = 10;
boolean result = (a != b);
// result will be true
>(greater than):
int a = 10;
int b = 5;
boolean result = (a > b);
// result will be true
<(less than):
int a = 5;
int b = 10;
boolean result = (a < b);
// result will be true
>=(greater than or equal to):
int a = 10;
int b = 10;
boolean result = (a >= b);
// result will be true
<=(less than or equal to):
int a = 5;
int b = 10;
boolean result = (a <= b);
// result will be true
Follow-up 2
How does the 'instanceof' operator work?
The instanceof operator in Java is used to check if an object is an instance of a particular class or implements a particular interface. It returns a boolean value (true or false) based on the result of the check. The syntax of the instanceof operator is as follows:
object instanceof Class
Here's an example:
class Animal {}
class Dog extends Animal {}
Animal animal = new Dog();
boolean result = (animal instanceof Dog);
// result will be true
Follow-up 3
What is the difference between '==' and 'equals()' method in Java?
In Java, the == operator is used to compare the references of two objects, while the equals() method is used to compare the contents or values of two objects. Here are the key differences between the two:
==operator:- Compares the memory addresses of the objects.
- Returns true if the references point to the same object.
equals()method:- Compares the contents or values of the objects.
- Returns true if the objects have the same content or values.
It's important to note that the equals() method can be overridden by classes to provide custom comparison logic, whereas the == operator cannot be overridden.
Live mock interview
Mock interview: Java Operators
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.