Control Structures โข 10 Exam-Style Questions โข 1Z0-808
๐ OCA Control Structures: if/else, switch cases, loops, scope & operatorsThis practice test focuses on Control Structures - one of the most heavily tested topics in the OCA exam (~7 questions). Master if-else statements, switch constructs, and loops to boost your exam score.
3: int counter = 5, total = 25; 4: while counter < 15 5: total--; 6: counter++; 7: System.out.println(counter + ", " + total);
The while loop condition on line 4 is missing parentheses. Java requires parentheses around while conditions: while (condition). This causes a compilation error.
Java Syntax Rule: All loop conditions must be enclosed in parentheses.
Line 4: while counter < 15 is invalid syntax.
Correct: while (counter < 15)
Because the code does not compile, the program never executes. Options A, B, C, and E all assume the code runs, but compilation fails before execution.
โ ๏ธ Common OCA Trap: This is a classic syntax trap question. Always check for missing parentheses in conditionals!
The break keyword immediately exits the switch block. Without a break, execution falls through to the next case. Therefore, only break correctly terminates a switch statement.
A switch executes the matched case and continues unless a break is encountered.
Option A is false: The default case does not end the switch automatically; you still need break to stop fall-through.
Option B is true: break exits the switch immediately and transfers control to the statement after the switch.
Option C is false: A case label does not exit anything โ it only marks where execution begins.
Option D is false: break does not jump to the next case; it leaves the switch entirely.
Option E is false: A switch statement is not a loop; it executes once based on the expression.
Key Rule: Only break stops switch fall-through.
The long type cannot be used in Java switch statements. Valid switch types include byte, short, char, int, enum, and String.
Valid switch types in Java:
โข Primitives: byte, short, char, int
โข enum types
โข String (since Java 7)
Invalid switch types:
โข long - too large a range
โข float and double - floating-point types
โข boolean - use if-else instead
Why not long? The switch statement requires values that can be mapped to a finite, manageable set of constants. The long type has a very large range (2^63 values), making it impractical for switch implementation.
Note: Wrapper types like Integer work in switch expressions due to auto-unboxing, but the underlying type must still be valid.
3: int value = 6;
4: long result = value * 3 - value++;
5: if(result < 15)
6: System.out.println("Low");
7: else
8: System.out.println("Medium");
9: else
10: System.out.println("High");
The code has two consecutive 'else' statements (lines 7 and 9), which is invalid Java syntax. Java allows if-else or if-else if-else, but not if-else-else.
This code has a syntax error in the if-else structure.
Lines 5-10 show:
if(result < 15) โ else โ else
The problem is having two consecutive 'else' clauses, which violates Java syntax rules.
Valid if-else structures:
1. if...else
2. if...else if...else
3. Nested if statements
Invalid: if...else...else
After the first 'else' statement, the if-else construct is complete. The second 'else' has no corresponding 'if' to attach to, causing a compilation error.
To fix: Change line 7 to else if(result < 25) instead of just else.
3: do {
4: int score = 5;
5: System.out.print(score++ + " ");
6: } while(score <= 20);
The variable score is declared inside the do-while loop body (line 4), so its scope is limited to that block. When the while condition on line 6 tries to reference score, the variable is out of scope, causing a compilation error.
Variable Scope Rule: Variables declared within a code block (enclosed in curly braces) are only accessible within that block.
Line 4: int score = 5; declares score inside the do block.
Line 6: The while condition tries to access score, but it's out of scope.
After the closing brace on line 5, the variable score no longer exists. The compiler cannot find score in the while condition, resulting in:
error: cannot find symbol - variable score
To fix: Declare score before the do loop:
int score = 5;
do {
System.out.print(score++ + " ");
} while(score <= 20);
3: final char first = 'E', last = 'H';
4: char rating = 'F';
5: switch(rating) {
6: case first:
7: case 'F': System.out.print("excellent");
8: case 'G': System.out.print("satisfactory"); break;
9: case last:
10: case 'J': System.out.print("needs improvement");
11: }
The switch matches case 'F', prints "excellent", then falls through (no break) to case 'G', prints "satisfactory", then breaks. Output: "excellentsatisfactory".
Execution trace:
1. rating = 'F'
2. Check case first ('E') โ no match
3. Check case 'F' โ MATCH!
4. Execute: System.out.print("excellent"); โ prints "excellent"
5. No break โ fall through to next case
6. Execute: System.out.print("satisfactory"); โ prints "satisfactory"
7. Hit break โ exit switch
Final output: excellentsatisfactory
Why compile? Final variables first and last are compile-time constants because they're initialized in their declaration. These are valid case labels.
Key Concept: Switch fall-through - execution continues to the next case unless a break is encountered.
class Demo {
public static void main(String args[]) {
final int num;
num = 10;
final int value = 8;
int choice = (int)(Math.random() * 6);
switch(choice) {
case num: { System.out.print("M"); } break;
case 3: System.out.print("N");
case 7: System.out.print("P"); break;
case value: System.out.print("O");
}
}
}
The variable num is declared as final but is not initialized in the same statement, making it a blank final. Blank finals are not compile-time constants and cannot be used in switch case labels. The code fails to compile at case num:.
Compile-Time Constant Rule: Switch case labels must be compile-time constants.
Line 2: final int num; - declared as final
Line 3: num = 10; - assigned later
This makes num a blank final - it's final but not initialized at declaration. Blank finals are assigned at runtime, not compile-time.
Line 7: case num: tries to use num as a case label.
Compiler error: constant expression required
Why value works: final int value = 8; is initialized in the same statement, making it a compile-time constant. This is valid for switch cases.
Key Rule: For a final variable to be a compile-time constant, it must be initialized in its declaration statement.
public class TestApp {
public static void main(String[] args) {
boolean active = true;
if (active = false) { System.out.println("inactive"); }
else if (active) { System.out.println("active"); }
}
}
The expression active = false is an assignment, not a comparison. It assigns false to active and evaluates to false, so the "inactive" branch doesn't execute. Then else if (active) is also false, so nothing prints.
Critical distinction: = (assignment) vs == (comparison)
Initial state: active = true
Line 4: if (active = false)
โข This is an assignment, not a comparison
โข active becomes false
โข Assignment expression evaluates to the assigned value: false
โข if (false) โ condition is false
โข "inactive" does NOT print
Line 5: else if (active)
โข Now active is false (due to assignment above)
โข if (false) โ condition is false
โข "active" does NOT print
Result: No branch executes โ no output
โ ๏ธ Common Bug: Using = instead of == in conditions is a frequent programming error!
for(int counter = 0; counter < 5;) {
counter = counter++;
System.out.println("Loop");
}
The expression counter = counter++ uses post-increment, which returns the original value before incrementing. This value is then assigned back to counter, effectively canceling the increment. counter remains 0 forever, creating an infinite loop.
Understanding post-increment:
counter++ returns the current value, then increments.
What happens in counter = counter++:
1. Save current value: temp = counter (temp = 0)
2. Increment counter: counter++ (counter becomes 1)
3. Return saved value: counter++ evaluates to temp (0)
4. Assignment: counter = 0 (back to original value!)
Result: counter never actually changes from 0.
Loop execution:
โข Start: counter = 0
โข Check: 0 < 5 โ true
โข Execute: counter = counter++ โ counter stays 0
โข Print "Loop"
โข Repeat forever (counter never reaches 5)
Note: The for loop has no increment section, so only the loop body can change counter. Since the body doesn't actually increment it, we get an infinite loop.
โ ๏ธ OCA Trap: This is a classic exam question testing understanding of post-increment behavior!
int y = 8;
while (y > 0) {
do {
y -= 1;
} while (y > 4);
y--;
System.out.println(y);
}
Initially y=8. The inner do-while decrements y until it's 4. Then y-- makes y=3, which is printed. On next iterations, y becomes 1 then -1. When y=-1, the outer while condition (y > 0) fails, stopping the loop.
Step-by-step execution:
Iteration 1:
โข Start: y = 8
โข do-while loop:
y = 7 (8 > 4 โ continue)
y = 6 (7 > 4 โ continue)
y = 5 (6 > 4 โ continue)
y = 4 (5 > 4 โ stop, now y = 4)
โข Exit do-while with y = 4
โข y-- โ y = 3
โข Print: 3
Iteration 2:
โข y = 3 (3 > 0 โ loop continues)
โข do-while: y = 2 (condition 2 > 4 is false, exit immediately)
โข y-- โ y = 1
โข Print: 1
Iteration 3:
โข y = 1 (1 > 0 โ loop continues)
โข do-while: y = 0 (condition 0 > 4 is false, exit)
โข y-- โ y = -1
โข Print: -1
Iteration 4:
โข y = -1 (-1 > 0 is false โ outer while stops)
Final output: 3 1 -1
Access 29 full-length practice tests with 1,624 questions covering all OCA exam topics
โ 29 full certification practice tests (56 questions each)
โ Chapter-wise practice by topic
โ Detailed explanations for every answer
โ Performance tracking and weak area identification
โ Pass guarantee or money back