Java Control Flow / If Else MCQs

1 min read

Control flow statements in Java determine the exact order in which code instructions and expressions execute during runtime. By default, code executes sequentially from top to bottom, but conditional branching constructs like if-else and switch allow programs to make decisions dynamically based on boolean evaluations. Furthermore, iteration structures including for, while, do-while, and the enhanced for-each loop handle repetitive tasks efficiently, while jump statements (break, continue, and labeled forms) provide precise control over loop execution paths and early termination.

1. Which of the following statements about the if-else statement in Java is correct?

a) The else block is mandatory whenever an if block is used.
b) The condition inside the if statement must evaluate to a boolean value.
c) An if statement can evaluate integer expressions directly without relational operators.
d) Multiple else blocks can be chained to a single if block.
Correct Answer: b) The condition inside the if statement must evaluate to a boolean value.
Explanation:
In Java, the expression inside the parentheses of an if statement must strictly evaluate to a boolean type (true or false). Unlike languages like C or C++, integers or references cannot be implicitly converted to boolean values.

2. What is the output of the following code snippet? int x = 10; if (x > 5) System.out.print("A"); else if (x > 8) System.out.print("B"); else System.out.print("C");

a) A
b) B
c) AB
d) C
Correct Answer: a) A
Explanation:
Java executes if-else if ladders sequentially. Since x = 10 satisfies the first condition x > 5, it prints 'A' and skips the remaining branches of the ladder.

3. Which data types are NOT permitted as a selector expression in a traditional Java switch statement?

a) byte and short
b) char and int
c) long and double
d) String and enum
Correct Answer: c) long and double
Explanation:
Traditional Java switch statements support byte, short, char, int, Character, Byte, Short, Integer, String, and enum. long, float, and double are not allowed because switch values must be convertible to 32-bit integers or supported types.

4. What happens if a break statement is omitted at the end of a case block in a switch statement?

a) A compile-time error occurs.
b) Execution terminates immediately.
c) Execution falls through to the next consecutive case block.
d) The default block is executed automatically.
Correct Answer: c) Execution falls through to the next consecutive case block.
Explanation:
Without a break statement, Java continues executing the statements of the subsequent cases regardless of whether their case labels match, a behavior known as fall-through.

5. Which loop structure guarantees that its body will execute at least once, regardless of the condition?

a) for loop
b) while loop
c) do-while loop
d) enhanced for loop
Correct Answer: c) do-while loop
Explanation:
The do-while loop evaluates its termination condition at the end of the loop block, ensuring that the code inside the loop executes at least once.

6. What is the result of the following for loop execution? for(int i = 0; i < 3; i++) { System.out.print(i); }

a) 123
b) 012
c) 0123
d) Infinite loop
Correct Answer: b) 012
Explanation:
The loop initializes i = 0, checks i < 3 (prints 0), increments i, and repeats for 1 and 2. When i becomes 3, the condition 3 < 3 is false, terminating the loop.

7. How many times will the following while loop execute? int x = 5; while (x > 0) { x--; }

a) 0 times
b) 4 times
c) 5 times
d) Infinite times
Correct Answer: c) 5 times
Explanation:
The loop runs for x = 5, 4, 3, 2, and 1. When x reaches 0, the condition 0 > 0 becomes false, resulting in exactly 5 iterations.

8. What is the primary function of the continue statement in Java loops?

a) It completely terminates the enclosing loop.
b) It skips the current iteration and proceeds to the next iteration of the loop.
c) It exits the current method and returns control to the caller.
d) It pauses execution for a specified number of milliseconds.
Correct Answer: b) It skips the current iteration and proceeds to the next iteration of the loop.
Explanation:
The continue statement bypasses the remaining statements in the current loop iteration and immediately evaluates the loop control expression or increment step for the next iteration.

9. Which statement correctly describes a labeled break statement in Java?

a) It can break out of any labeled block or nested loops from an inner scope.
b) It replaces the need for exception handling in multi-threaded programs.
c) It restarts the execution of a labeled loop from the beginning.
d) It allows a switch statement to jump directly to a specific case label.
Correct Answer: a) It can break out of any labeled block or nested loops from an inner scope.
Explanation:
A labeled break allows program control to transfer to the statement immediately following the labeled enclosing statement, making it useful for breaking out of deeply nested loops.

10. What will be the output of this code snippet? int i = 1; for(; i <= 2; i++) { System.out.print(i); }

a) Compile-time error due to missing initialization in the for loop.
b) 12
c) 123
d) Infinite loop
Correct Answer: b) 12
Explanation:
Parts of a for loop header are optional. Since i is already initialized outside, the loop starts directly with condition check i <= 2 and prints 1 and 2.

11. What is the output of the following code snippet? int x = 2; switch(x) { case 1: System.out.print("One"); case 2: System.out.print("Two"); case 3: System.out.print("Three"); default: System.out.print("Default"); }

a) Two
b) TwoThreeDefault
c) TwoThree
d) Compile-time error
Correct Answer: b) TwoThreeDefault
Explanation:
Due to the absence of break statements after each case, execution falls through from case 2 to case 3 and the default block, printing all subsequent messages.

12. Which of the following is a valid syntax for an infinite for loop in Java?

a) for(;;) {}
b) for(true) {}
c) for(int i=0; ; i++) {}
d) Both a and c
Correct Answer: d) Both a and c
Explanation:
Both for(;;) and for(int i=0; ; i++) create infinite loops in Java. for(true) is invalid because true is a boolean value, not an expression statement.

13. What is the output of the following code? int count = 0; do { count++; } while(count < 0); System.out.print(count);

a) 0
b) 1
c) Infinite loop
d) Compile-time error
Correct Answer: b) 1
Explanation:
The do-while loop executes its block once, incrementing count from 0 to 1. Then the condition 1 < 0 is evaluated as false, terminating the loop and printing 1.

14. Which control flow keyword is used to explicitly throw an exception object?

a) throws
b) throw
c) catch
d) finally
Correct Answer: b) throw
Explanation:
The throw statement is used to trigger an exception manually within code execution, whereas throws is used in method signatures to declare checked exceptions.

15. What is the purpose of the finally block in Java exception control flow?

a) To catch any unexpected runtime errors.
b) To execute cleanup code regardless of whether an exception occurred or was caught.
c) To define code that only executes when an exception is successfully thrown.
d) To optimize loop execution speed.
Correct Answer: b) To execute cleanup code regardless of whether an exception occurred or was caught.
Explanation:
The finally block guarantees execution after try and catch blocks complete, making it ideal for resource cleanup such as closing streams or database connections.

16. What will happen if a return statement is placed inside the try block of a method that also contains a finally block?

a) The finally block is bypassed entirely.
b) The finally block executes right before the method actually returns control.
c) A compile-time error occurs.
d) The program terminates abruptly.
Correct Answer: b) The finally block executes right before the method actually returns control.
Explanation:
Even if a return statement is encountered in the try or catch block, the finally block executes before the method transfers control back to the caller.

17. Which of the following constructs can be used with the enhanced for loop (for-each loop)?

a) Any array and any class implementing java.lang.Iterable
b) Only primitive arrays
c) Any class implementing java.util.Map directly
d) Only java.util.ArrayList objects
Correct Answer: a) Any array and any class implementing java.lang.Iterable
Explanation:
The enhanced for loop works seamlessly with arrays and any collection or custom object whose class implements the java.lang.Iterable interface.

18. What is the output of the following code snippet? int[] arr = {1, 2, 3}; for(int val : arr) { val = val * 2; } System.out.print(arr[1]);

a) 1
b) 2
c) 4
d) 6
Correct Answer: b) 2
Explanation:
The enhanced for loop uses a local variable that receives a copy of each array element's value. Modifying val does not mutate the underlying elements inside the array arr.

19. What is the primary difference between a while loop and a for loop in Java?

a) A while loop cannot be infinite, whereas a for loop can.
b) There is no functional difference; any for loop can be written as a while loop and vice-versa.
c) A for loop cannot handle boolean conditions.
d) A while loop requires an explicit increment statement inside its header.
Correct Answer: b) There is no functional difference; any for loop can be written as a while loop and vice-versa.
Explanation:
Syntactically different, for and while loops are logically interchangeable. A for loop is typically used when the number of iterations is known beforehand.

20. What will be printed by the following code? int x = 5; if (x == 5) int y = 10; System.out.print(y);

a) 10
b) 5
c) Compile-time error
d) Runtime exception
Correct Answer: c) Compile-time error
Explanation:
In Java, a single-line if statement body without curly braces cannot declare a local variable because variable declarations are declarations, not full statements.

21. Which of the following is true regarding nested loops with break statements?

a) A break statement without a label terminates all nested loops simultaneously.
b) A break statement without a label terminates only the innermost loop containing it.
c) A break statement is illegal inside nested loops.
d) A break statement automatically skips to the outer loop's next iteration.
Correct Answer: b) A break statement without a label terminates only the innermost loop containing it.
Explanation:
An unlabeled break statement exits only the innermost enclosing loop or switch statement, leaving outer loops unaffected.

22. What happens if the expression inside a switch statement evaluates to null?

a) It automatically executes the default case.
b) It throws a NullPointerException at runtime.
c) It results in a compile-time error.
d) It skips the entire switch block silently.
Correct Answer: b) It throws a NullPointerException at runtime.
Explanation:
If a String or boxed primitive type passed as a selector expression to a Java switch statement is null, Java throws a NullPointerException at runtime.

23. What is the output of the following code? int i = 0; for(; i < 2; i++) { System.out.print(i); } System.out.print(i);

a) 012
b) 011
c) 01
d) Compile-time error
Correct Answer: a) 012
Explanation:
The loop prints 0 and 1 while i < 2. After the loop terminates, i has been incremented to 2. The final print outputs 2, resulting in 012.

24. Which keyword is used in Java to handle an exception thrown within a try block?

a) handle
b) catch
c) except
d) trap
Correct Answer: b) catch
Explanation:
The catch block specifies the type of exception it can handle and contains the code executed when that exception occurs.

25. What is the output of the following conditional expression (ternary operator)? int res = (10 > 20) ? 30 : 40; System.out.print(res);

a) 10
b) 20
c) 30
d) 40
Correct Answer: d) 40
Explanation:
The ternary operator evaluates 10 > 20 as false, so it selects the second value (40).

26. Can a switch statement expression evaluate to a floating-point number (float or double)?

a) Yes, always.
b) Yes, if cast to an integer.
c) No, it causes a compile-time error.
d) Yes, but only in Java 14 and above.
Correct Answer: c) No, it causes a compile-time error.
Explanation:
Floating-point types are never permitted as switch expression selectors due to precision issues associated with floating-point comparisons.

27. What will be the output of this code? int x = 1; if (x > 0) if (x > 2) System.out.print("A"); else System.out.print("B");

a) A
b) B
c) AB
d) No output
Correct Answer: b) B
Explanation:
This is an example of the dangling-else problem. The else clause binds to the nearest preceding if (if (x > 2)). Since x = 1 is not greater than 2, the else block executes, printing 'B'.

28. What is the output of the following code snippet? for (int i = 0; i < 5; i++) { if (i == 2) continue; System.out.print(i); }

a) 01234
b) 0134
c) 012
d) 234
Correct Answer: b) 0134
Explanation:
When i == 2, the continue statement skips the print statement for that iteration, resulting in 0134.

29. Which of the following describes a multi-catch block introduced in Java 7?

a) Catching multiple exceptions in separate try blocks.
b) Catching multiple exception types in a single catch block using the pipe (|) symbol.
c) Catching all exceptions using a single catch(Exception e) clause.
d) Catching nested exceptions automatically without declaration.
Correct Answer: b) Catching multiple exception types in a single catch block using the pipe (|) symbol.
Explanation:
Java 7 allows catching multiple exception types in a single catch block, reducing code duplication.

30. What will happen if a variable is declared inside the initialization section of a for loop header?

a) Its scope is limited to the block of the for loop.
b) It remains accessible throughout the entire enclosing method.
c) It causes a compile-time error.
d) It becomes a static class variable.
Correct Answer: a) Its scope is limited to the block of the for loop.
Explanation:
Variables declared in a for loop initialization statement have their scope restricted exclusively to the loop body and header.

31. What is the output of the following code? boolean flag = false; if (flag = true) System.out.print("True"); else System.out.print("False");

a) True
b) False
c) Compile-time error
d) No output
Correct Answer: a) True
Explanation:
The expression flag = true is an assignment operator. It assigns true to flag and returns true, making the if condition evaluate to true and printing 'True'.

32. Which of the following keywords is used to transfer control out of a method entirely?

a) break
b) continue
c) return
d) exit
Correct Answer: c) return
Explanation:
The return statement immediately terminates execution of the current method and returns control to the point where the method was invoked.

33. What is the output of the following nested loop? for(int i=1; i<=2; i++) { for(int j=1; j<=2; j++) { if(i == j) break; System.out.print(i + "" + j); } }

a) 12
b) 21
c) 11 22
d) No output
Correct Answer: b) 21
Explanation:
For i=1: when j=1, breaks inner loop. For i=2: when j=1, prints 21; when j=2, breaks. Thus, it prints 21.

34. What is a major rule regarding case constants in a standard Java switch statement?

a) They can be duplicate values.
b) They must be compile-time constants (literals or final constants).
c) They can be runtime variables.
d) They must be sorted in descending order.
Correct Answer: b) They must be compile-time constants (literals or final constants).
Explanation:
Every case label value must be a compile-time constant expression; runtime variables or non-final variables cannot be used as case values.

35. What is the output of the following code snippet? int x = 0; while(x < 3) { System.out.print(x); x++; }

a) 123
b) 012
c) 0123
d) Infinite loop
Correct Answer: b) 012
Explanation:
The loop prints 0, 1, and 2 while x < 3, incrementing x after each print statement.

36. Which of the following is true regarding the default label in a switch statement?

a) It is strictly mandatory in every switch block.
b) It can be placed anywhere within the switch block, though typically placed at the end.
c) There can be multiple default labels in a single switch.
d) It must always be followed by a break statement.
Correct Answer: b) It can be placed anywhere within the switch block, though typically placed at the end.
Explanation:
The default label is optional and can technically be placed anywhere within the switch statement, although conventions dictate placing it at the end.

37. What will happen if you attempt to compile and run code with an unreachable catch block for a specific exception that is already caught by a preceding broader exception block?

a) It runs successfully with a warning.
b) It throws a runtime exception.
c) It causes a compile-time error ('exception has already been caught').
d) The compiler automatically reorders the catch blocks.
Correct Answer: c) It causes a compile-time error ('exception has already been caught').
Explanation:
Java enforces strict catch block ordering. More specific exceptions must be caught before broader exceptions; otherwise, a compile-time error occurs.

38. What is the output of the following snippet? int sum = 0; for(int i = 1; i <= 4; i += 2) { sum += i; } System.out.print(sum);

a) 4
b) 10
c) 6
d) 16
Correct Answer: a) 4
Explanation:
The loop iterates for i = 1 (sum = 1) and i = 3 (sum = 1 + 3 = 4). Next iteration i = 5 fails the condition. Total sum is 4.

39. Which exception control flow feature allows automatic resource management without an explicit finally block?

a) Try-with-resources statement
b) AutoClose block
c) Resource-safe catch
d) Managed-finally clause
Correct Answer: a) Try-with-resources statement
Explanation:
Introduced in Java 7, the try-with-resources statement ensures that each resource is closed at the end of the statement, provided the resource implements AutoCloseable.

40. What is the output of the following code? int x = 5; if (x > 10) System.out.print("Greater"); else System.out.print("Lesser");

a) Greater
b) Lesser
c) Compile-time error
d) Runtime error
Correct Answer: b) Lesser
Explanation:
Since x = 5 is not greater than 10, the condition evaluates to false, executing the else block and printing 'Lesser'.

41. What is the output of the following code snippet? int i = 0; for(; i < 3; ) i++; System.out.print(i);

a) 0
b) 2
c) 3
d) Compile-time error
Correct Answer: c) 3
Explanation:
The loop increments i from 0 to 3 inside the loop body. When i becomes 3, the condition 3 < 3 fails, and 3 is printed.

42. Which of the following is an accurate restriction regarding switch expressions introduced in Java 14?

a) They do not allow arrow syntax.
b) Every branch must produce a value or complete abruptly if used in an assignment context.
c) They cannot return values.
d) They require a break statement in every branch when using arrow syntax.
Correct Answer: b) Every branch must produce a value or complete abruptly if used in an assignment context.
Explanation:
When a switch expression is used to assign values, all branches must return a valid result or throw an exception to ensure type safety.

43. What will be the output of the following loop? for(int i = 5; i > 0; i -= 2) { System.out.print(i); }

a) 531
b) 531-1
c) 54321
d) Infinite loop
Correct Answer: a) 531
Explanation:
The loop starts at i = 5, decrements by 2 each iteration, printing 5, then 3, then 1. When i becomes -1, the condition i > 0 fails.

44. What is the primary role of the assert statement in Java control flow?

a) To test assumptions about program state during debugging and testing.
b) To handle checked exceptions automatically.
c) To replace standard unit testing frameworks completely.
d) To optimize loop compilation speeds.
Correct Answer: a) To test assumptions about program state during debugging and testing.
Explanation:
An assert statement enables developers to test boolean conditions during debugging. If disabled at runtime, assertions have no performance impact.

45. What happens if an assertion fails when assertions are enabled?

a) An ArithmeticException is thrown.
b) An AssertionError is thrown.
c) The program terminates silently.
d) A compilation warning is triggered.
Correct Answer: b) An AssertionError is thrown.
Explanation:
When an assertion condition evaluates to false with assertions enabled, an AssertionError is thrown, which is a subclass of Error.

46. What is the output of the following code? int x = 10; if (x == 10) int a = 5; else int b = 6;

a) 5
b) 6
c) Compile-time error
d) 10
Correct Answer: c) Compile-time error
Explanation:
Local variable declarations cannot be the direct target of an if or else branch without enclosing curly braces because declarations are not statements.

47. Which of the following statements about recursion as a control flow mechanism is true?

a) Recursive methods do not require a base case.
b) Excessive recursion without a proper base case can lead to a StackOverflowError.
c) Recursion always executes faster than iterative loops in Java.
d) Recursion cannot be used to traverse trees.
Correct Answer: b) Excessive recursion without a proper base case can lead to a StackOverflowError.
Explanation:
Every recursive call allocates new stack frames. Without a terminating base case, it exhausts thread stack memory, throwing a StackOverflowError.

48. What will be printed by the following code? int a = 5, b = 10; if ((a = 3) == b) System.out.print("Equal"); else System.out.print("Not Equal");

a) Equal
b) Not Equal
c) Compile-time error
d) Runtime error
Correct Answer: b) Not Equal
Explanation:
The assignment a = 3 sets a to 3 and returns 3. Comparing 3 == 10 is false, so it executes the else branch and prints 'Not Equal'.

49. What is the output of the following code? int x = 0; for (int i = 0; i < 3; i++) { x = x + i; } System.out.print(x);

a) 3
b) 2
c) 1
d) 0
Correct Answer: a) 3
Explanation:
Iterations: i=0 -> x=0; i=1 -> x=1; i=2 -> x=3. Total final value of x is 3.

50. Which keyword is used to pass control back to the caller when an exception cannot be handled locally in a method?

a) throw
b) throws
c) rethrow
d) pass
Correct Answer: b) throws
Explanation:
The throws keyword is used in a method signature to declare that the method might throw one or more checked exceptions.

51. What will be the output of the following code? int i = 0; while (i < 3) { System.out.print(i); i++; }

a) 012
b) 123
c) 0123
d) Infinite loop
Correct Answer: a) 012
Explanation:
Prints 0, 1, and 2 as i increments from 0 to 2 before stopping when i reaches 3.

52. Which of the following describes short-circuit evaluation in Java logical control flow operators?

a) Both operands are always evaluated regardless of the first operand's value.
b) Evaluation stops as soon as the final boolean outcome is determined by the first operand.
c) It causes a short-circuit error if operands are non-boolean.
d) It forces parallel evaluation of both conditions.
Correct Answer: b) Evaluation stops as soon as the final boolean outcome is determined by the first operand.
Explanation:
In &&, if the left operand is false, the right operand is not evaluated. In ||, if the left operand is true, the right operand is not evaluated.

53. What is the output of the following switch expression? String day = "TUE"; int val = switch (day) { case "MON" -> 1; case "TUE", "WED" -> 2; default -> 0; }; System.out.print(val);

a) 1
b) 2
c) 0
d) Compile-time error
Correct Answer: b) 2
Explanation:
The enhanced switch expression uses multiple case labels and an arrow operator to yield 2, which is assigned to val and printed.

54. Can a try block exist without a catch block?

a) No, every try block must have at least one catch block.
b) Yes, as long as it has a finally block.
c) Yes, a try block can stand completely alone.
d) Only if declared inside an abstract class.
Correct Answer: b) Yes, as long as it has a finally block.
Explanation:
A try block must be followed by either at least one catch block, a finally block, or both.

55. What is the output of the following code snippet? int x = 5; if (x > 3) if (x < 10) System.out.print("Inside"); else System.out.print("Outer Else");

a) Inside
b) Outer Else
c) No output
d) Compile-time error
Correct Answer: a) Inside
Explanation:
Since x = 5 satisfies both x > 3 and x < 10, it executes the innermost print statement, outputting 'Inside'.

56. What will happen if the loop condition evaluates to true on the very first check in a do-while loop compared to a while loop?

a) The while loop executes, but do-while throws an error.
b) Both loops will execute their body successfully.
c) Only the do-while loop will execute.
d) Both loops fail to execute.
Correct Answer: b) Both loops will execute their body successfully.
Explanation:
When the initial condition is true, both while and do-while loops execute their bodies.

57. What is the output of the following code? int x = 10; for (int i = 0; i < 2; i++) { x -= i; } System.out.print(x);

a) 10
b) 9
c) 8
d) 7
Correct Answer: b) 9
Explanation:
Iterations: i=0 -> x = 10 - 0 = 10; i=1 -> x = 10 - 1 = 9. Final value of x is 9.

58. Which of the following is an illegal combination of try-catch-finally components?

a) try with catch
b) try with finally
c) try with catch and finally
d) try alone without catch or finally
Correct Answer: d) try alone without catch or finally
Explanation:
A try block cannot exist by itself in Java; it must be accompanied by at least one catch clause or a finally block.

59. What is the output of the following code snippet? int count = 0; for(int i = 0; i < 10; i++) { if(i % 3 == 0) count++; } System.out.print(count);

a) 3
b) 4
c) 5
d) 10
Correct Answer: b) 4
Explanation:
Numbers from 0 to 9 where i % 3 == 0 are 0, 3, 6, and 9. There are 4 such numbers, so count becomes 4.

60. What is the output of the following code? int x = 2; switch(x) { case 1: System.out.print("A"); break; case 2: System.out.print("B"); case 3: System.out.print("C"); break; default: System.out.print("D"); }

a) B
b) BC
c) BCD
d) Compile error
Correct Answer: b) BC
Explanation:
Matches case 2 (prints 'B') and falls through to case 3 (prints 'C') because there is no break after case 2.

61. Which control flow statement allows jumping to a designated code section marked with an identifier in Java?

a) goto
b) labeled break and continue
c) jump
d) transfer
Correct Answer: b) labeled break and continue
Explanation:
While goto is a reserved keyword in Java, it is not supported. Instead, Java provides labeled break and continue statements.

62. What will happen if you attempt to use a non-final local variable inside a lambda expression or inner class control flow block?

a) It compiles successfully with default values.
b) It causes a compile-time error ('variable must be effectively final').
c) It throws a runtime exception.
d) The variable is automatically made static.
Correct Answer: b) It causes a compile-time error ('variable must be effectively final').
Explanation:
Local variables accessed from within lambda expressions or inner classes must be final or effectively final.

63. What is the output of the following code snippet? int i = 5; while (--i > 2) { System.out.print(i); }

a) 543
b) 43
c) 432
d) 54
Correct Answer: b) 43
Explanation:
Pre-decrement --i: i becomes 4 (prints 4), then i becomes 3 (prints 3). Output: 43.

64. Which of the following control structures is best suited when executing code iteratively based on a collection's elements without indexing?

a) Traditional for loop
b) Enhanced for loop (for-each)
c) Do-while loop
d) Switch statement
Correct Answer: b) Enhanced for loop (for-each)
Explanation:
The enhanced for loop simplifies iteration over collections and arrays by eliminating explicit index management.

65. What is the output of the following code? int x = 1; switch (x) { case 1 -> System.out.print("One"); case 2 -> System.out.print("Two"); } System.out.print("Done");

a) OneDone
b) OneTwoDone
c) Done
d) Compile-time error
Correct Answer: a) OneDone
Explanation:
Arrow syntax in modern Java switch statements does not fall through. It automatically breaks after executing the matched branch.

66. Can an if statement execute without curly braces?

a) No, curly braces are always mandatory.
b) Yes, but only the single statement immediately following the if is bound to it.
c) Yes, all subsequent statements in the method are bound to it.
d) Only inside static blocks.
Correct Answer: b) Yes, but only the single statement immediately following the if is bound to it.
Explanation:
Without curly braces, the scope of the if condition covers only the single statement immediately following it.

67. What is the output of the following code snippet? int a = 10; if (a++ == 10) { System.out.print(a); }

a) 10
b) 11
c) Compile-time error
d) No output
Correct Answer: b) 11
Explanation:
The post-increment expression a++ evaluates to 10 for the comparison, making the condition true. Immediately after evaluation, a increments to 11, which is printed.

68. Which of the following is true regarding the execution order of try, catch, and finally blocks when an exception occurs?

a) finally executes before catch.
b) catch executes before try.
c) try executes, then the matching catch executes, and finally the finally block executes.
d) finally executes only if an exception is NOT caught.
Correct Answer: c) try executes, then the matching catch executes, and finally the finally block executes.
Explanation:
When an exception occurs in try, control jumps to the corresponding catch block, after which the finally block executes unconditionally.

69. What is the output of the following code? int x = 0; for(int i = 0; i < 5; i++) { if(i == 3) break; x += i; } System.out.print(x);

a) 3
b) 6
c) 10
d) 0
Correct Answer: a) 3
Explanation:
Accumulation happens for i = 0 (0), i = 1 (1), and i = 2 (3). When i = 3, the loop breaks. Total sum is 3.

70. What will happen if a method declares that it throws a checked exception, but the caller neither catches it nor declares it in its own throws clause?

a) It runs successfully.
b) It causes a compile-time error ('unhandled exception').
c) It throws a RuntimeException at runtime.
d) The compiler ignores it automatically.
Correct Answer: b) It causes a compile-time error ('unhandled exception').
Explanation:
Java's checked exception mechanism requires callers to either handle checked exceptions using try-catch or declare them using throws.

71. What is the output of the following snippet? int x = 5; if (--x == 4 || x++ == 4) { System.out.print(x); }

a) 4
b) 5
c) 6
d) No output
Correct Answer: a) 4
Explanation:
Pre-decrement --x changes x to 4. The left side (4 == 4) evaluates to true. Because of short-circuit evaluation, the right side is never evaluated. x remains 4 and is printed.

72. Which of the following loops is recommended when the number of iterations depends entirely on a dynamic user input condition checked after execution?

a) for loop
b) do-while loop
c) Enhanced for loop
d) Standard while loop
Correct Answer: b) do-while loop
Explanation:
A do-while loop is ideal for menu-driven programs where the block must execute at least once before checking whether to repeat.

73. What is the output of the following code? int i = 0; for(System.out.print("A"); i < 2; System.out.print("B"), i++) { System.out.print("C"); }

a) ACBCB
b) ACBC
c) ABCABC
d) Compile-time error
Correct Answer: a) ACBCB
Explanation:
Initialization prints A. Condition checks and prints C, then update prints B, repeating until the loop terminates. Total output: ACBCB.

74. Can a switch statement evaluate expressions containing enum constants?

a) No, enums are never supported in switch statements.
b) Yes, enums are fully supported selector types in Java switch statements.
c) Only if converted to strings first.
d) Only in legacy Java versions.
Correct Answer: b) Yes, enums are fully supported selector types in Java switch statements.
Explanation:
Enums are fully supported in Java switch statements, allowing case labels to match enum constants directly.

75. What is the output of the following code snippet? int x = 10; if (x > 5) if (x > 15) System.out.print("A"); else System.out.print("B");

a) A
b) B
c) AB
d) No output
Correct Answer: b) B
Explanation:
The inner else binds to the inner if (x > 15). Since x = 10 is not greater than 15, the inner else branch executes, printing 'B'.

76. Which of the following is true regarding multi-threaded control flow and exception handling?

a) An exception thrown in one thread can be caught by a catch block in another thread directly.
b) Each thread has its own call stack; exceptions must be caught within the same thread unless using Thread.UncaughtExceptionHandler.
c) Threads automatically share try-catch contexts.
d) Exceptions terminate all active threads in the JVM immediately.
Correct Answer: b) Each thread has its own call stack; exceptions must be caught within the same thread unless using Thread.UncaughtExceptionHandler.
Explanation:
Because threads execute on separate call stacks, unhandled exceptions terminate only that specific thread.

77. What is the output of the following code? int x = 0; LABEL: { if (x == 0) break LABEL; System.out.print("Inside"); } System.out.print("Outside");

a) InsideOutside
b) Outside
c) Compile-time error
d) Inside
Correct Answer: b) Outside
Explanation:
Java allows labeling arbitrary blocks. The break LABEL statement terminates the labeled block immediately, outputting 'Outside'.

78. What will happen if you put statements between the try block and its corresponding catch block?

a) It compiles and runs normally.
b) It causes a compile-time error ('syntax error, insert "catch"').
c) The intermediate statements are ignored.
d) It creates a warning.
Correct Answer: b) It causes a compile-time error ('syntax error, insert "catch"').
Explanation:
A catch or finally block must immediately follow the try block without any intervening code.

79. What is the output of the following code snippet? int val = 2; switch(val) { case 1: System.out.print("1"); case 2: System.out.print("2"); case 3: System.out.print("3"); } System.out.print("End");

a) 2End
b) 23End
c) 123End
d) End
Correct Answer: b) 23End
Explanation:
Matches case 2 (prints 2), falls through to case 3 (prints 3), and finishes by printing End.

80. Which of the following statements about break and continue keywords is correct?

a) Both can be used inside if-else blocks without loops or switches.
b) break exits a loop or switch, whereas continue skips the rest of the current iteration.
c) continue terminates the enclosing loop entirely.
d) break can be used without any label or context.
Correct Answer: b) break exits a loop or switch, whereas continue skips the rest of the current iteration.
Explanation:
break terminates execution of the enclosing loop or switch, while continue jumps directly to the evaluation step for the next iteration.

81. What is the output of the following code? int x = 5; if (x > 0) System.out.print("A"); else if (x > 3) System.out.print("B"); else System.out.print("C");

a) A
b) AB
c) C
d) B
Correct Answer: a) A
Explanation:
Since x = 5 satisfies the first condition x > 0, it prints 'A' and skips the remaining branches.

82. What happens if an exception is thrown inside a finally block?

a) It is ignored by the JVM.
b) It suppresses any previous exception thrown in the try or catch blocks.
c) It is automatically caught by the preceding catch block.
d) It prevents method execution permanently.
Correct Answer: b) It suppresses any previous exception thrown in the try or catch blocks.
Explanation:
If an exception is thrown in a finally block, it takes precedence and overrides any exception that was thrown in the try or catch block.

83. What is the output of the following code snippet? int sum = 0; for(int i = 1; i <= 3; i++) { for(int j = 1; j <= 2; j++) { sum += i; } } System.out.print(sum);

a) 6
b) 12
c) 18
d) 8
Correct Answer: b) 12
Explanation:
Inner loop runs 2 times for each outer loop iteration. i=1 adds 2; i=2 adds 4; i=3 adds 6. Total sum = 12.

84. Which of the following describes an 'effectively final' variable in Java?

a) A variable explicitly declared with the final keyword.
b) A variable whose value is never changed after its initial assignment, even without the final keyword.
c) A variable that changes values continuously inside loops.
d) A variable initialized inside a static block.
Correct Answer: b) A variable whose value is never changed after its initial assignment, even without the final keyword.
Explanation:
An effectively final variable is not declared final, but its value is never modified after initialization.

85. What is the output of the following code? int x = 3; switch(x) { case 1: System.out.print("One"); break; case 2: System.out.print("Two"); break; default: System.out.print("Default"); }

a) One
b) Two
c) Default
d) No output
Correct Answer: c) Default
Explanation:
Since x = 3 does not match cases 1 or 2, control falls through to the default branch, printing 'Default'.

86. Can you use continue statement inside a switch statement?

a) Yes, always.
b) No, continue can only be used inside loops.
c) Yes, if labeled.
d) Only in enhanced switch expressions.
Correct Answer: b) No, continue can only be used inside loops.
Explanation:
Using a continue statement outside of a loop construct causes a compile-time error.

87. What is the output of the following code snippet? int x = 0; for (int i = 0; i < 3; i++, x++) { x += i; } System.out.print(x);

a) 3
b) 4
c) 5
d) 6
Correct Answer: b) 4
Explanation:
Tracing the loop iterations and updates yields a final value of 4 for x.

88. Which of the following is a checked exception in Java that must be explicitly caught or declared?

a) NullPointerException
b) ArrayIndexOutOfBoundsException
c) IOException
d) ArithmeticException
Correct Answer: c) IOException
Explanation:
IOException is a checked exception inherited directly from Exception, requiring mandatory handling or declaration.

89. What is the output of the following code? int x = 10; if (x < 5) System.out.print("A"); else if (x < 20) System.out.print("B"); else System.out.print("C");

a) A
b) B
c) C
d) BC
Correct Answer: b) B
Explanation:
Since x = 10 is not less than 5, but is less than 20, the second condition is true, printing 'B'.

90. What is the purpose of a labeled continue statement in nested loops?

a) It restarts the innermost loop.
b) It skips the current iteration of the outer labeled loop and proceeds with its next iteration.
c) It terminates all loops entirely.
d) It replaces exception handling.
Correct Answer: b) It skips the current iteration of the outer labeled loop and proceeds with its next iteration.
Explanation:
A labeled continue targets an outer enclosing loop, skipping the rest of its current iteration.

91. What is the output of the following code snippet? int i = 0; while (i < 2) { i++; if (i == 1) continue; System.out.print(i); }

a) 01
b) 2
c) 12
d) No output
Correct Answer: b) 2
Explanation:
When i = 1, continue skips the print statement. When i = 2, it prints 2. Output is 2.

92. Can a switch statement evaluate expressions of type boolean?

a) Yes, always.
b) No, booleans are not allowed in switch statements.
c) Only in Java 17 and above.
d) Yes, if wrapped in Boolean objects.
Correct Answer: b) No, booleans are not allowed in switch statements.
Explanation:
Boolean types are not permitted in switch expressions because if-else conditionals are designed for binary boolean branching.

93. What is the output of the following code? int x = 4; switch (x) { case 2, 4, 6 -> System.out.print("Even"); default -> System.out.print("Odd"); }

a) Even
b) Odd
c) Compile-time error
d) No output
Correct Answer: a) Even
Explanation:
Modern Java enhanced switch syntax supports multiple comma-separated case constants in a single branch, matching 4 and printing 'Even'.

94. What happens when an unhandled exception propagates up the call stack to the main method and remains uncaught?

a) The JVM prints the exception stack trace and terminates the program.
b) The program automatically restarts.
c) The compiler catches it retroactively.
d) It converts into a warning message.
Correct Answer: a) The JVM prints the exception stack trace and terminates the program.
Explanation:
If an exception reaches the top-level main thread without being caught anywhere in the call stack, the JVM prints its stack trace and exits.

95. What is the output of the following code snippet? int x = 1; for(; x <= 3; x++) { System.out.print(x); }

a) 012
b) 123
c) 1234
d) Infinite loop
Correct Answer: b) 123
Explanation:
The loop runs for x = 1, 2, and 3, printing each value before terminating when x becomes 4.

96. Which of the following is true regarding a multi-catch block in Java 7 and later?

a) The exception parameter in a multi-catch block is implicitly final.
b) You can catch multiple exception types even if they are subclasses of one another.
c) It requires a separate finally block for each exception type caught.
d) It cannot be used with custom user-defined exceptions.
Correct Answer: a) The exception parameter in a multi-catch block is implicitly final.
Explanation:
In Java, the exception parameter in a multi-catch block is implicitly final, meaning you cannot assign a new value to it.

97. What happens when an exception is thrown inside a try block and a matching catch block is not found in the current method?

a) The program silently ignores the exception.
b) The exception is automatically converted into a warning message.
c) The exception propagates up the call stack to the calling method.
d) The JVM shuts down immediately without executing finally blocks.
Correct Answer: c) The exception propagates up the call stack to the calling method.
Explanation:
If a method does not handle an exception locally, it propagates up the call stack to the calling method.

98. Which of the following best describes the behavior of the break statement when used inside a switch expression?

a) It is mandatory at the end of every arrow-based branch.
b) It is not required for arrow-based branches because fall-through is prevented automatically.
c) It causes a compile-time error if used in a switch expression.
d) It restarts the switch expression from the beginning.
Correct Answer: b) It is not required for arrow-based branches because fall-through is prevented automatically.
Explanation:
Modern Java switch expressions using arrow syntax automatically prevent fall-through, making explicit break statements redundant.

99. Which of the following is an invalid loop header declaration in Java?

a) for (int i = 0, j = 10; i < j; i++, j--)
b) for (int i = 0; i < 5; )
c) for ( ; ; )
d) for (int i = 0; boolean flag = true; i++)
Correct Answer: d) for (int i = 0; boolean flag = true; i++)
Explanation:
The condition part of a for loop must evaluate to a boolean expression, not a variable declaration statement.

100. What is the primary purpose of the try-with-resources statement introduced in Java 7?

a) To optimize multi-threaded CPU execution speeds.
b) To ensure that resources like files or sockets are closed automatically when no longer needed.
c) To bypass the requirement of handling checked exceptions.
d) To allow multiple return statements in a single try block.
Correct Answer: b) To ensure that resources like files or sockets are closed automatically when no longer needed.
Explanation:
The try-with-resources statement ensures automatic closure of any object implementing AutoCloseable.

101. Can a finally block be executed if a System.exit(0) call is executed inside the preceding try block?

a) Yes, always.
b) No, because System.exit() terminates the Java Virtual Machine immediately.
c) Yes, but only if an exception is thrown simultaneously.
d) Only in multi-threaded environments.
Correct Answer: b) No, because System.exit() terminates the Java Virtual Machine immediately.
Explanation:
Calling System.exit() shuts down the JVM abruptly, preventing any subsequent code or finally blocks from executing.

102. Which of the following is true regarding switch expressions yielding values using the yield keyword?

a) It is used in traditional switch statements with colons.
b) It is used inside code blocks in switch expressions to produce a value.
c) It replaces the break statement in all loops.
d) It is a modifier used in method declarations.
Correct Answer: b) It is used inside code blocks in switch expressions to produce a value.
Explanation:
When a switch expression branch uses a code block rather than a single expression, the yield keyword is required to supply the value returned.

103. What is the output of the following code snippet? int count = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == j) count++; } } System.out.print(count);

a) 2
b) 3
c) 6
d) 9
Correct Answer: b) 3
Explanation:
The condition i == j evaluates to true when (0,0), (1,1), and (2,2), running 3 times and incrementing count to 3.

104. Which of the following is an unchecked exception and typically indicates serious application configuration or programming flaws?

a) IOException
b) SQLException
c) NullPointerException
d) ClassNotFoundException
Correct Answer: c) NullPointerException
Explanation:
NullPointerException is a runtime exception subclassing RuntimeException, representing programming bugs like dereferencing null.

105. What is the output of the following code snippet? int i = 1; while (i < 5) { i += i; } System.out.print(i);

a) 4
b) 8
c) 5
d) 16
Correct Answer: b) 8
Explanation:
Iterations: i = 1 -> 2 -> 4 -> 8. When i = 8, 8 < 5 is false, terminating and printing 8.

106. What is the output of the following code snippet? int x = 1; for (int i = 0; i < 3; i++) { x = x * 2; } System.out.print(x);

a) 4
b) 8
c) 16
d) 2
Correct Answer: b) 8
Explanation:
Iterations: i = 0 (2); i = 1 (4); i = 2 (8). Final value of x is 8.

107. Can a catch block catch an Error object such as OutOfMemoryError?

a) No, errors cannot be caught in Java.
b) Yes, because Error subclasses Throwable, though catching errors is generally discouraged.
c) Only if declared as a checked exception.
d) Only inside finalizer methods.
Correct Answer: b) Yes, because Error subclasses Throwable, though catching errors is generally discouraged.
Explanation:
Both Exception and Error inherit from Throwable. You can technically catch Error, but errors represent abnormal, catastrophic conditions.

108. Which of the following is required for a custom user-defined exception to act as a checked exception?

a) It must extend RuntimeException.
b) It must extend Exception directly or via another checked exception.
c) It must implement AutoCloseable.
d) It must be declared as static.
Correct Answer: b) It must extend Exception directly or via another checked exception.
Explanation:
To create a checked exception, a custom class must inherit from java.lang.Exception without extending RuntimeException.

109. What happens if an exception is thrown inside a catch block and there is an associated finally block?

a) The finally block is skipped entirely.
b) The finally block executes before the exception propagates further.
c) The exception from the catch block is suppressed immediately without execution.
d) The program terminates silently.
Correct Answer: b) The finally block executes before the exception propagates further.
Explanation:
The finally block always executes when control leaves a try-catch construct, even if an exception was thrown inside the catch block.

110. Which of the following data structures or types cannot be used as an argument in an enhanced for loop?

a) Standard Java arrays
b) Instances of java.util.List
c) Instances of java.util.Map directly without conversion
d) Instances of java.util.Set
Correct Answer: c) Instances of java.util.Map directly without conversion
Explanation:
Maps do not implement Iterable directly; you must call entrySet(), keySet(), or values() to iterate over them.

111. What is the output of the following code snippet? int i = 0; for (; i < 2; System.out.print(i), i++);

a) 01
b) 0
c) 12
d) Infinite loop
Correct Answer: a) 01
Explanation:
The loop body is empty. The update section prints i and increments it for i = 0 and i = 1, resulting in 01.

112. What happens if an assertion condition evaluates to false when assertions are disabled?

a) An AssertionError is thrown immediately.
b) The assertion statement is ignored completely with zero performance impact.
c) It triggers a compile-time warning.
d) The program terminates with an exit code of 1.
Correct Answer: b) The assertion statement is ignored completely with zero performance impact.
Explanation:
When assertions are disabled at runtime, assertion statements are skipped entirely by the JVM, incurring no execution overhead.

113. What is the output of the following code snippet? int i = 3; while (--i > 0) { System.out.print(i); }

a) 321
b) 21
c) 210
d) 32
Correct Answer: b) 21
Explanation:
Pre-decrement --i: i becomes 2 (prints 2), then i becomes 1 (prints 1). Output is 21.
← Previous: Java Collections Frame Work MCQs
Next →: Java Exception Handling MCQs
Java Operators MCQs

Java Operators MCQs

Java operators are special symbols and keywords used to perform operations on variables and values, governing arithmetic calculations, logical evaluations,…

By MCQs Generator
JavaScript Event Handling MCQs

JavaScript Event Handling MCQs

Event handling in JavaScript allows developers to build interactive web applications by listening for user interactions such as mouse clicks,…

By MCQs Generator
C++ Classes and Objects - MCQs

C++ Classes and Objects - MCQs

In C++, a class is a fundamental building block of Object-Oriented Programming (OOP) that acts as a user-defined blueprint for…

By MCQs Generator