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

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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!

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:
java ,exception handling

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}