Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 35
Question ID: UKOCP37185
Given code:
- package com.udayankhattry.ocp;
- class Outer {
- public void print(int x) {
- class Inner {
- public void getX() {
- System.out.println(++x);
- }
- }
- Inner inner = new Inner();
- inner.getX();
- }
- }
- public class Test {
- public static void main(String[] args) {
- new Outer().print(100);
- }
- }
What will be the result of compiling and executing Test class?
- A 100
- B 101
- C Compilation error
- D Runtime exception
Reveal correct answer
Correct answer: C
Explanation
UKOCP37185:
class Inner is method local inner class and it is accessing parameter variable x.
Starting with JDK 8, a method local inner class can access local variables and parameters of the enclosing block that are final or effectively final.
But the statement System.out.println(++x); tries to increment the value of variable x and hence compilation error.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
