Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard

Question 90

Question ID: UKOCP51494


Consider below code of Test.java file:


What will be the result of compiling and executing Test class?

  • A a = 2, b = 4, c = 7, d = 9, res = false
  • B a = 2, b = 4, c = 8, d = 10, res = false
  • C a = 2, b = 4, c = 7, d = 9, res = true
  • D a = 2, b = 4, c = 8, d = 10, res = true
  • E a = 3, b = 5, c = 8, d = 10, res = false
  • F a = 3, b = 5, c = 8, d = 10, res = true
Reveal correct answer

Correct answer: A

Explanation

UKOCP51494:

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 variable name, method name or package name but it cannot be used as a class or interface name.


At Line n1, a infers to int type.

At Line n2, b infers to int type.

At Line n3, c infers to int type.

At Line n4, d infers to int type.


Given expression:

--a + --b < 1 && c++ + d++ > 1;

--a + --b < 1 && (c++) + (d++) > 1; //postfix has got highest precedence

(--a) + (--b) < 1 && (c++) + (d++) > 1; //prefix comes after postfix

{(--a) + (--b)} < 1 && {(c++) + (d++)} > 1; //Then comes binary +. Though parentheses are used but I used curly brackets, just to explain.

[{(--a) + (--b)} < 1] && [{(c++) + (d++)} > 1]; //Then comes relational operator (<,>). I used square brackets instead of parentheses.

This expression is left with just one operator, && and this operator is a binary operator so works with 2 operands, left operand [{(--a) + (--b)} < 1] and right operand [{(c++) + (d++)} > 1]

Left operand of && must be evaluated first, which means [{(--a) + (--b)} < 1] must be evaluated first.


[{2 + (--b)} < 1] && [{(c++) + (d++)} > 1]; //a=2, b=5, c=7, d=9

[{2 + 4} < 1] && [{(c++) + (d++)} > 1]; //a=2, b=4, c=7, d=9

[6 < 1] && [{(c++) + (d++)} > 1];

false && [{(c++) + (d++)} > 1];


&& is short circuit operator, hence right operand is not evaluated and false is returned.


Output of the given program is: a = 2, b = 4, c = 7, d = 9, res = false

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.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need