Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 42
Given code of Test.java file:
- package com.udayan.ocp;
- public class Test {
- private static void checkStatus(boolean flag) {
- assert flag : flag = true;
- }
- public static void main(String[] args) {
- checkStatus(false);
- }
- }
What will be the result of executing Test class with below command?
java -ea:com.udayan... com.udayan.ocp.Test
- A No output and program terminates successfully
- B AssertionError is thrown and program terminates abruptly
- C Compilation error
Reveal correct answer
Correct answer: B
Explanation
'java -ea:com.udayan...' enables the assertion in com.udayan package and its sub packages.
Test class is defined under 'com.udayan.ocp' package, hence assertion is enabled for Test class.
assert flag : flag = true; => flag is a boolean variable, so 'assert flag' has no issues and right expression must not be void.
'flag = true' assigns true to flag and true is returned as well. Hence no issues with right side as well.
On execution, flag is false, hence AssertionError is thrown and program terminates abruptly.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
