Java Operators: Types, Subtypes, Rules, Examples & Interview Questions
Java Operators: Types, Subtypes, Rules, Examples & Interview Questions
Operators in Java are symbols that perform operations on variables and values. They are grouped into major types and subtypes.
1. Arithmetic Operators ➕➖✖️➗ (%)
Subtypes & Rules
Declaration Rule:
Declare numeric types (int
, float
, double
) before using.
int a = 10, b = 3;
int result = a + b;
SDET Interview Q:
Q: What will 10 / 4
output if both are integers?
A: 2
— Integer division truncates decimal.
2. Relational (Comparison) Operators ⚖️
Subtypes & Rules
Declaration Rule:
Operands must be of the same type or compatible.
int a = 10, b = 5;
boolean result = a > b;
SDET Interview Q:
Q: Difference between ==
and .equals()
on Strings?
A: ==
checks reference, .equals()
checks content.
3. Logical Operators && || !
Subtypes & Rules
Declaration Rule:
Both operands must be boolean expressions.
boolean result = (age > 18) && (salary > 50000);
SDET Interview Q:
Q: What is short-circuit evaluation?
A: In &&
, if first is false, second is skipped. In ||
, if first is true, second is skipped.
4. Assignment Operators ๐️
Subtypes & Rules
Declaration Rule:
Variable must be declared before usage.
int x = 20;
x += 10; // now x = 30
SDET Interview Q:
Q: Can you use +=
with Strings?
A: Yes, it acts as string concatenation.
5. Unary Operators ☝️
Subtypes & Rules
Declaration Rule:
Works on numeric or boolean types.
int x = 5;
int y = ++x; // y = 6, x = 6
SDET Interview Q:
Q: Difference between x++
and ++x
in a print statement?
A: x++
prints first, then increments. ++x
increments first.
6. Bitwise Operators ⚙️
Subtypes & Rules
Declaration Rule:
Works only with integer types (int
, byte
, short
, long
).
int result = 5 & 3; // 0101 & 0011 = 0001 = 1
SDET Interview Q:
Q: Why use bitwise over logical?
A: Faster, used in performance-critical code or flags.
7. Ternary Operator ❓
Syntax and Rule:
variable = (condition) ? valueIfTrue : valueIfFalse;
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
Declaration Rule:
- Result must match variable type.
- Used only for single conditional expressions.
SDET Interview Q:
Q: Can ternary operator replace if-else
?
A: Yes, for simple conditions.
8. instanceof
Operator ๐
Usage and Rule
Syntax:
object instanceof ClassName
Example:
String name = "John";
if (name instanceof String) {
System.out.println("It’s a String");
}
Declaration Rule:
- Object must not be null for meaningful result.
- Used for runtime type checking.
SDET Interview Q:
Q: Why is instanceof
useful in testing?
A: To verify object types in dynamic PageFactory or polymorphic UI elements.
9. Type Casting Operators ๐
Subtypes
Declaration Rule:
- Implicit: Auto-conversion from small to large.
- Explicit: Manual cast needed to avoid data loss.
SDET Interview Q:
Q: What is type casting?
A: Converting one data type to another; explicit casts may lose data...
Comments
Post a Comment