๐Ÿงช OCA Java Practice Test 2

Control Structures โ€ข 10 Exam-Style Questions โ€ข 1Z0-808

๐Ÿ“š OCA Control Structures: if/else, switch cases, loops, scope & operators

๐Ÿ“š Topics Covered in Practice Test 2

About This Practice Test

This 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.

๐Ÿ’ก Tip: Pay close attention to syntax details, variable scope, and fall-through behavior in switch statements. These are common exam traps!
Question 1 EASY ๐Ÿ“Œ While Loop Syntax
What is the output of the following code snippet?
3: int counter = 5, total = 25;
4: while counter < 15
5:     total--;
6: counter++;
7: System.out.println(counter + ", " + total);
A. 15, 10
B. 15, 11
C. 16, 10
D. The code will not compile because of line 4.
E. A syntax error occurs before the loop executes.

โœ… Correct Answer: D

The while loop condition on line 4 is missing parentheses. Java requires parentheses around while conditions: while (condition). This causes a compilation error.

๐Ÿ“– Detailed Explanation:

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!

Question 2 EASY ๐Ÿ“Œ Switch Statement Control Flow
Which of the following statements about Java switch statements is TRUE?
A. The default clause terminates the switch block automatically
B. The break keyword exits the switch construct immediately
C. A case label causes immediate exit from the switch block
D. The break statement transfers control to the subsequent case section
E. Switch statements loop while their condition evaluates to true

โœ… Correct Answer: B

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.

๐Ÿ“– Detailed Explanation:

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.

Question 3 EASY ๐Ÿ“Œ Switch Expression Types
Which of the following data types CANNOT be used as a switch expression in Java?
A. char
B. enum
C. String
D. long
E. All of the above can be used

โœ… Correct Answer: D

The long type cannot be used in Java switch statements. Valid switch types include byte, short, char, int, enum, and String.

๐Ÿ“– Detailed Explanation:

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.

Question 4 EASY ๐Ÿ“Œ Control Structures
What is the result of the following code?
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");
A. Low
B. Medium
C. High
D. Compilation error
E. Runtime exception

โœ… Correct Answer: D

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.

๐Ÿ“– Detailed Explanation:

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.

Question 5 MEDIUM ๐Ÿ“Œ Variable Scope
What is the output of the following code snippet?
3: do {
4:     int score = 5;
5:     System.out.print(score++ + " ");
6: } while(score <= 20);
A. 567891011121314151617181920
B. 5678910111213141516171819
C. 56789101112131415161718192021
D. The code will not compile because of line 6.
E. The code contains an infinite loop and does not terminate.

โœ… Correct Answer: D

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.

๐Ÿ“– Detailed Explanation:

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);

Question 6 MEDIUM ๐Ÿ“Œ Switch Fall-Through
What is the result of the following code snippet?
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: }
A. excellent
B. excellentsatisfactory
C. The code will not compile because of line 3.
D. The code will not compile because of line 6.
E. The code will not compile because of lines 6 and 9.

โœ… Correct Answer: B

The switch matches case 'F', prints "excellent", then falls through (no break) to case 'G', prints "satisfactory", then breaks. Output: "excellentsatisfactory".

๐Ÿ“– Detailed Explanation:

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.

Question 7 MEDIUM ๐Ÿ“Œ Switch Case Constants
What is the output of the following code?
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");
        }
    }
}
A. Prints 'M' or 'N' or 'P' or nothing, depending on the random value
B. Prints 'M' or 'MNP' or 'NP' or 'P' or nothing, depending on the random value
C. The code will not compile because of line 5
D. The code will not compile because of line 7
E. The code will not compile because of multiple errors

โœ… Correct Answer: D

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:.

๐Ÿ“– Detailed Explanation:

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.

Question 8 MEDIUM ๐Ÿ“Œ Assignment vs Comparison
What is the output of the following code?
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"); }
    }
}
A. inactive
B. active
C. Compilation error
D. No output
E. Runtime exception

โœ… Correct Answer: D

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.

๐Ÿ“– Detailed Explanation:

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!

Question 9 HARD ๐Ÿ“Œ Post-Increment Trap
What is the result of the following code?
for(int counter = 0; counter < 5;) {
    counter = counter++;
    System.out.println("Loop");
}
A. Prints 'Loop' 5 times
B. Prints 'Loop' 6 times
C. Compilation error
D. Infinite loop printing 'Loop'
E. No output

โœ… Correct Answer: D

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.

๐Ÿ“– Detailed Explanation:

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!

Question 10 HARD ๐Ÿ“Œ Nested Loops
In the following while-do structure, what will be printed?
int y = 8;
while (y > 0) {
    do {
        y -= 1;
    } while (y > 4);
    y--;
    System.out.println(y);
}
A. 4 2 0
B. 3 1 -1
C. 3 1 -1 -3
D. Infinite Loop

โœ… Correct Answer: B

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.

๐Ÿ“– Detailed Explanation:

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

Ready for More Practice Tests?

Access 29 full-length practice tests with 1,624 questions covering all OCA exam topics

What You'll Get:

โ†’ 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

Start Free Trial Now โ†’