Multiple choice technology programming languages

Given: class Plane { static String s = "-"; public static void main(String[] args) { new Plane().s1() ; System.out.println(s); } void sl() { try { s2(); catch (Exception e) { s += "c"; } } void s2() throws Exception { s3(); s += "2"; s3(); s += "2b"; } void s3() throws Exception { throw new Exception(); } } What is the result?

  1. -

  2. -c

  3. -c2

  4. -2c

  5. -c22b

  6. -2c2b

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

To solve this question, we need to trace the execution of the code and see how the value of the variable s changes.

Starting with the main method, it creates a new instance of the Plane class and calls its method s1().

In the s1() method, it calls the method sl().

In the sl() method, it calls the method s2(). Since s2() throws an exception, execution of the sl() method is transferred to the catch block. Here, it appends "c" to the value of s.

Control is then transferred back to the s1() method, which then returns to the main method. Finally, the value of s is printed to the console, which is "-c" since the catch block was executed.

Therefore, the answer is: B. -c

AI explanation

In this classic SCJP-style question, s3() throws an exception on its first call inside s2(), which immediately propagates out of s2() (skipping the s += "2" and everything after) and is caught back in the calling method, which appends "c" to the string. Since the exception is thrown before any of the string-concatenation lines inside s2() execute, the final printed value is just "-c".