Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Quiz: Exception Handling in Java

DZone's Guide to

Java Quiz: Exception Handling in Java

The latest advanced Java quiz from DZone's resident quizmaster!

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Last Week's Answer: Using Inheritance and Static Methods

int x = 2;
static int s = 3;

MyClass mc = new MyClass();
x=2, s=3;
   super(3)
      this();
          x+=4; x=2+4 =6;
       x += x + 20; // ignore this value because it is a parameter
    x -= 7 = 6-7= -1 
    s += x = 3 -1 = 2     
mc.method(); 
   x+= 7;
   x = -1+7=6;
   super.method();
      x += 35 = 6+35 = 41; // ignore this value, see next step. 
new MyClass(); // returns a new object, the value of x reset to 2.
   x=2, s=2; // the last value of “s” is 2 because it is static.
   super(3)
      this();
          x+=4; x=2+4 =6;
       x += x + 20; //ignore this x because it is a parameter.
    x -= 7 = 6-7=-1
    s += x = 2 -1 = 1

The result is that the code writes "1" to the standard output

This Week's Quiz: Exception Handling in Java

This quiz is aimed at advanced Java programmers.

Purpose

  1. To introduce some tricks and behaviors of Java exceptions.

  2. To train and improve your imagination.

What is written to the standard output as the result of executing the following code?

public class MyClass {

    int x;

    public void method(int i){
        try {
            if(i > 2) {
                i = (1 / 0) + Integer.parseInt("x");
            }else {
                i = Integer.parseInt("x") + (1 / 0);
            }
        }catch(ArithmeticException e) {
            x += 4;
        }catch(RuntimeException e) {
            x += 3;
        }catch(Exception e) {
            x += 5;
        }finally {
            x += 2;
        }
        x ++ ;
    }
    public static void main(String[] args){
        MyClass mc = new MyClass();
        mc.method(3);
        mc.method(2);
        System.out.print(mc.x);
    }
}

Let us know your thoughts in the comments, and check out Sar's site here!

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
java ,exception handling

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}