Java OCA OCP Practice Question 2383

Question

Examine the following code and select the correct options:

public class Main {                          // line 1 
    public static void main(String[] args) { // line 2 
        int num1 = 12;                       // line 3 
        float num2 = 17.8f;                  // line 4 
        boolean b = true;                    // line 5 
        boolean returnVal = num1 >= 12 
                      && num2 < 4.567        // line 6 
                      || b == true;              
        System.out.println(returnVal);       // line 7 
    }                                        // line 8 
}                                            // line 9 
a  Code prints false 
b  Code prints true 
c  Code will print true if code on line 6 is modified to the following: 

   boolean returnVal = (num1 >= 12 && num2 < 4.567) || b == true; 

d  Code will print true if code on line 6 is modified to the following: 

   boolean returnVal = num1 >= 12 && (num2 < 4.567 || b == false); 


b, c

Note

Option (a) is incorrect because the code prints true.

Option (d) is incorrect because the code prints false.

The code in option (c) uses parentheses to indicate which expression should evaluate prior to the rest.

Here are the steps of execution:.

boolean returnVal = (num1 >= 12 && num2 < 4.567) || b == true; 
returnVal = false || b == true; 
returnVal = true; 

The original code in the question doesn't use parentheses to group the expressions.

In this case, because the operator && has a higher operator precedence than ||, the expression 'num1 >= 12 && num2 < 4.567' will be the first expression to execute.

Here are the steps of execution:.

boolean returnVal = num1 >= 12 && num2 < 4.567 || b == true; 
returnVal = false || b == true; 
returnVal = true; 



PreviousNext

Related