Java SE 8 Programmer II: Exam 1Z0-809 - Question Solution

Rate of Interest Program

Question

Given: class RateOfInterest{ public static void main (String[]args){ int rateOfInterest = 0; String accountType = "LOAN"; switch (accountType){ case "RD"; rateOfInterest = 5; break; case "FD"; rateOfInterest = 10; break; default: assert false: "No interest for this account"; //line n1 } System.out.println ("Rate of interest:" + rateOfInterest); } } and the command: java ""ea RateOfInterest What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The given code defines a class named RateOfInterest with a main method. The main method initializes an integer variable named rateOfInterest to 0 and a String variable named accountType to "LOAN". Then it uses a switch statement to set the value of rateOfInterest based on the value of accountType.

In the switch statement, there are two cases:

  • case "RD": sets the value of rateOfInterest to 5 and then breaks out of the switch statement.
  • case "FD": sets the value of rateOfInterest to 10 and then breaks out of the switch statement.

If the value of accountType is not "RD" or "FD", then the default case is executed. This case contains an assert statement that always evaluates to false and throws an AssertionError with the message "No interest for this account". The assert statement is followed by a comment that indicates the line number (line n1).

The command "java -ea RateOfInterest" executes the RateOfInterest class with assertion enabled. The "-ea" flag is used to enable assertions.

Now let's analyze the options:

A. Rate of interest: 0 This is the default value of rateOfInterest before the switch statement is executed. However, this option is not possible if the program executes without errors or exceptions.

B. An AssertionError is thrown. This is the expected behavior if the accountType is not "RD" or "FD". The assert statement in the default case evaluates to false, which causes the AssertionError to be thrown.

C. No interest for this account This is the message specified in the AssertionError that is thrown if the default case is executed.

D. A compilation error occurs at line n1. This is not possible as the code compiles without any errors.

Therefore, the correct answer is option B, "An AssertionError is thrown."