Java OCA OCP Practice Question 724

Question

What will the following code print?

public class Main {
   public int m(int seed) {
      if (seed > 10)
         return seed % 10;
      int x = 0;/*from w ww  . j  a  va2 s. co m*/
      try {
         if (seed % 2 == 0)
            throw new Exception("No Even no.");
         else
            return x;
      } catch (Exception e) {
         return 3;
      } finally {
         return 7;
      }
   }

   public static void main(String args[]) {
      int amount = 100, seed = 6;
      switch (new Main().m(6)) {
      case 3:
         amount = amount * 2;
      case 7:
         amount = amount * 2;
      case 6:
         amount = amount + amount;
      default:
      }
      System.out.println(amount);
   }
}

Select 1 option

  • A. It will not compile.
  • B. It will throw an exception at runtime.
  • C. 800
  • D. 200
  • E. 400


Correct Option is  : E

Note

When you pass 6 to m (),

if (seed%2 == 0) throw new Exception ("No Even no.");

is executed and the exception is caught by the catch block where it tries to return 3;

But as there is a finally associated with the try/catch block, it is executed before anything is returned.

As finally has return 7;, this value supersedes 3.

In fact, this method will always return 7 if seed <= 10.

In the switch there is no break statement.

So both -

case 7: amount = amount * 2; 

and

case 6: amount = amount + amount; 

are executed. so the final amount becomes 400.




PreviousNext

Related