Java OCA OCP Practice Question 2547

Question

Consider the following program:

public class Main {
        public static void main(String[] args) {
                String two = "2";
                System.out.println("1 + 2 + 3 + 4 = "
                        + 1 + Integer.parseInt(two) + 3 + 4); // PARSE
        }
}

Which one of the following options correctly describes the behavior of this program?

  • a) When compiled, this program will give a compiler error in line marked with comment PARSE for missing catch handler for NumberFormatException.
  • b) When executed, the program prints the following: 1 + 2 + 3 + 4 = 1234.
  • c) When executed, the program prints the following: 1 + 2 + 3 + 4 = 10.
  • d) When executed, the program prints the following: 1 + 2 + 3 + 4 = 127.
  • e) When executed, the program prints the following: 1 + 2 + 3 + 4 = 19.
  • f) When executed, the program throws a NumberFormatException in the line marked with comment PARSE.


b)

Note

The string concatenation operator works as follows: if both operands are numbers, it performs the addition; otherwise, it performs string concatenation.

The operator checks from left operand to right.

Here, the first operand is string; therefore all operands are concatenated.

Note that parseInt need not catch NumberFormatException since it is a RuntimeException; so the lack of the catch handler will not result in a compiler error.

Since the parseInt method succeeds, the program does not throw NumberFormatException.




PreviousNext

Related