Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 83
Question ID: UKOCP54125
Given code of Test.java file:
- package com.udayankhattry.ocp;
- public class Test {
- static int a = 10000;
- static {
- a = -a--;
- }
- {
- a = -a++;
- }
- public static void main(String[] args) {
- System.out.println(a);
- }
- }
What is the result?
- A Compilation error
- B -10000
- C 10000
- D 9999
- E -9999
Reveal correct answer
Correct answer: B
Explanation
UKOCP54125:
Variable 'a' is of static type, so both static and instance initializer blocks can access it. Given code compiles successfully.
We are not creating the instance of Test class, so instance initializer block will not be executed. Only static initializer block will be executed in this case.
If static variable declaration / initialization statements are present along with static initializer blocks, then these are invoked in top to bottom order. So, for the given code, order of execution will be:
1. static int a = 10000;
and then
2. static { a = -a--; }
Statement 1, initializes variable 'a' to 10000.
Let's solve the statement inside static initializer block:
a = -a--; [a = 10000].
a = -(a--); [a = 10000] Postfix operator has got higher precedence than unary operator.
a= -(10000); [a = 9999] Use the value of a (10000) in the expression and after that decrement the value of a to 9999.
a = -10000; [a = -10000] Assigns -10000 to a
System.out.println(a); inside main method prints -10000
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
