Java OCA OCP Practice Question 2571

Question

Consider the following program and predict the output:

class Test {//ww w .  j a v a 2s  .c o  m
     private static int mem = 0;
    public static void foo() {
             try {
                     mem = mem + 1;
             }
             catch(Exception e) {
                     e.printStackTrace();
             }
             finally {
                     mem = mem + 1;
             }
     }
     public static void main(String []args) {
             foo();
             System.out.println(mem);
     }
}
  • a) 0
  • b) 1
  • c) 2
  • d) 3


c)

Note

The variable mem is 0 initially.

It is incremented by one in the try block and is incremented further in the finally block to 2.

Note that finally will always execute irrespective of whether an exception is thrown in the try block or not.

Hence, the program will print 2.




PreviousNext

Related