Java Interview Questions
Control Statements and Switch Theory
1. What are the different types of control statements in Java?
Java has three main types of control statements:
1. Decision-making statements: if, if-else, switch
2. Loop statements: for, while, do-while
3. Jump statements: break, continue, return
2. What is the difference between if and switch statements?
If statement: Used for boolean conditions, can test complex expressions, evaluates conditions sequentially
Switch statement: Used for equality testing of discrete values, more efficient for multiple choices, uses jump table internally
3. What are the valid data types for switch expression?
In Java, switch expression can be of these types:
- byte, short, char, int (primitive types)
- Byte, Short, Character, Integer (wrapper classes)
- String (since Java 7)
- enum types
Note: long, float, double, boolean and their wrapper classes are NOT allowed
4. What is the purpose of the break statement in switch?
The break statement in switch is used to terminate the switch block and prevent fall-through behavior. Without break, execution will continue to the next case statements until a break is encountered or the switch ends.
5. What is switch fall-through and when is it useful?
Fall-through occurs when multiple case labels execute the same code block without break statements. It's useful when multiple values should trigger the same action:
switch(day) {
case 1: case 2: case 3: case 4: case 5:
System.out.println("Weekday"); break;
case 6: case 7:
System.out.println("Weekend"); break;
}
6. What is the default case in switch statement?
The default case is optional and executes when no case matches the switch expression. It's similar to the else clause in if-else statements. The default case can be placed anywhere in the switch block, but conventionally it's placed at the end.
7. What are the enhancements to switch in Java 14?
Java 14 introduced switch expressions with:
- Arrow syntax (->) instead of colon
- Multiple case labels separated by commas
- Yield keyword for returning values
- No fall-through by default in new syntax
Example: String result = switch(day) { case 1,2,3,4,5 -> "Weekday"; case 6,7 -> "Weekend"; default -> "Invalid"; };
8. What is the difference between if-else if ladder and switch?
If-else if ladder: Better for range checks, complex boolean expressions, non-discrete values
Switch: Better for equality checks with discrete values, more readable for multiple choices, potentially faster due to jump table optimization
9. Can we use null in switch statement?
No, using null in switch expression will throw NullPointerException at runtime. Always check for null before using in switch:
if(str != null) {
switch(str) { ... }
}
10. What is the ternary operator and how does it differ from if-else?
The ternary operator (?:) is a shorthand for if-else that returns a value:
result = (condition) ? value1 : value2;
Differences: Ternary is an expression (returns value), if-else is a statement. Ternary is more concise but can be less readable for complex conditions.
11. What are nested if statements and what are their limitations?
Nested if are if statements inside other if statements. Limitations include:
- Reduced readability (deeply nested code)
- Increased complexity
- Harder to maintain and debug
Alternative: Use guard clauses, extract methods, or use switch when appropriate
12. How does switch work with enums?
Switch works well with enums and provides type safety:
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
Day today = Day.MON;
switch(today) {
case MON: case TUE: case WED: case THU: case FRI:
System.out.println("Weekday"); break;
case SAT: case SUN:
System.out.println("Weekend"); break;
}
Note: Use enum constants without qualifying (MON instead of Day.MON)
13. What is short-circuit evaluation in logical operators?
Short-circuit evaluation means the second operand is evaluated only if necessary:
- && (AND): If first operand is false, second is not evaluated
- || (OR): If first operand is true, second is not evaluated
This improves performance and prevents exceptions in conditions like: if(obj != null && obj.isValid())
14. Can we use floating-point numbers in switch statement?
No, floating-point numbers (float, double) and their wrapper classes are NOT allowed in switch statements due to precision issues. Switch requires exact matching, which is problematic with floating-point comparisons.
15. What are labeled break and continue statements?
Labeled statements allow breaking or continuing specific loops in nested scenarios:
outer: for(int i=0; i<3; i++) {
inner: for(int j=0; j<3; j++) {
if(i*j == 4) break outer; // breaks outer loop
}
}
This is useful for breaking out of multiple nested loops simultaneously.
16. What is the difference between == and equals() in condition checks?
== compares object references (memory addresses) for objects, and values for primitives
equals() compares the actual content/values of objects
For strings: str1 == str2 checks if same object, str1.equals(str2) checks if same content
17. How does switch handle String comparisons internally?
Switch with Strings uses the hashCode() method for efficiency. It first compares hash codes, then uses equals() for verification in case of hash collisions. This makes String switches nearly as efficient as integer switches.
18. What are the best practices for using control statements?
- Use switch for multiple discrete values
- Use if-else for range checks and complex conditions
- Always use braces {} even for single statements
- Avoid deep nesting (max 2-3 levels)
- Use default case in switch for error handling
- Prefer early returns and guard clauses
- Use final for constants in switch cases