Java OCA OCP Practice Question 3111

Question

Given this class definition:

public class Main {
    public static void main(String[] args) {
        int score = 0;
        int num = 0;
        assert ++num > 0 : "failed";
        int res = score / num;
        System.out.println(res);
    }
}

Choose the correct option assuming that this program is invoked as follows:

java -ea Main
  • a) this program crashes by throwing java.lang.AssertionError with the message "failed"
  • b) this program crashes by throwing java.lang.ArithmeticException with the message "/ by zero"
  • c) this program prints: 0
  • d) this program prints "failed" and terminates normally


c)

Note

the condition within the assert statement ++num > 0 holds true because num's value is 1 with the pre-increment expression ++num.

the expression 0 / 1 results in the value 0 and hence the output.

options a) and d) the assertion condition holds true; hence neither java.lang.AssertionError is thrown nor the message "failed" get printed.

Since the assertions are enabled by passing the option "-ea" this does not result in divide-by-zero. If the assertion were not disabled, it would have crashed by throwing java.lang.ArithmeticException with the message "/ by zero"




PreviousNext

Related