Conditionals
& vs && and | vs ||
Key Differences
&and|: Bitwise operators (for numbers) or Logical operators (for booleans, no short-circuit).&&and||: Logical operators (only for booleans, with short-circuiting).
Common Bug
Using & or | instead of && or || can cause hidden bugs:
Rule of Thumb
- Use
&&and||for logical conditions (better for safety and performance). - Use
&and|only when both sides must be evaluated (rare cases).
Ternary Operator (? :)
What is the Ternary Operator?
The ternary operator is a shorthand for if-else statements. It has the syntax:
When to Use
- Use the ternary operator for simple conditional assignments.
- Avoid using it for complex logic as it can reduce code readability.
Enhanced switch Expression (Java 12+)
What is the Enhanced switch?
The enhanced switch expression simplifies the syntax by removing the need for break statements and allows returning values directly. Example:
When to Use
- Use the enhanced
switchfor cleaner and more concise code. - It is especially useful when returning values directly from a
switch.