Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 32
Question ID: UKOCP14052
Consider below code of the Test.java file:
- package com.udayankhattry.ocp;
- public class Test {
- public static void main(String[] args) {
- int ctr = 100;
- one: for (var i = 0; i < 10; i++) {
- two: for (var j = 0; j < 7; j++) {
- three: while (true) {
- ctr++;
- if (i > j) {
- break one;
- } else if (i == j) {
- break two;
- } else {
- break three;
- }
- }
- }
- }
- System.out.println(ctr);
- }
- }
What is the result?
- A Compilation error
- B 100
- C 101
- D 102
- E 103
- F 104
-
G
105
-
H
106
Reveal correct answer
Correct answer: D
Explanation
UKOCP14052:
Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for-loops. For example,
var x = "Java"; //x infers to String
var m = 10; //m infers to int
The identifier var is not a keyword, hence var can still be used as the variable name, method name, package name, or loop's label but it cannot be used as a class or interface name.
For the 1st loop variable, 'i' infers to int type, so no issues for 1st loop, and for the 2nd loop variable 'j' infers to int type, so no issues for 2nd loop as well.
Let's check the iteration:
1st iteration of loop one: i = 0
1st iteration of loop two: j = 0
1st iteration of loop three: ctr = 101. As i == j evaluates to true, hence break two; gets executed, which takes the control out of loop two and hence to the increment expression (i++) of loop one.
2nd iteration of loop one; i = 1
1st iteration of loop two: j = 0
1st iteration of loop three; ctr = 102. As i > j evaluates to true, hence break one; gets executed, which takes the control out of the loop one.
System.out.println(ctr); prints 102 onto the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
