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

Java Quiz 4: Passing a Parameter to a Constructor

DZone's Guide to

Java Quiz 4: Passing a Parameter to a Constructor

Catch up with the answer to the last Java Quiz about exception handling and dive into a new one about passing parameters to constructors.

· Java Zone
Free Resource

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

Before we start with this week's quiz, here is the answer to Java Quiz 3: Handling Exceptions

  1. By passing the parameters 13 and 0 to the method print, the statement nr = accounts[i] / i2; causes an ArrayIndexOutOfBoundsException. The reason is that element 13 doesn't exist. The equation nr = accounts[i] / i2; first tries to access element 13, then divides the number by zero. The code doesn't handle ArrayIndexOutOfBoundsExceptions, but the Exception is a generic Exception handler. The statement System.out.print("T"); writes T to the standard output.

  2. By passing the parameters 12 and 0 to the method print, the statement nr = accounts[i] / i2; divides zero by zero, which causes an ArithmeticException. The statement System.out.print("S"); writes S to the standard output. The correct answer is: D.

Here is the quiz for today!

What happens when the following program is compiled and run?

public class MyClass {  
    int y = 3;     
    public MyClass(int i) {    
        y += i;  
    }  
    public MyClass(int i, int i2) {    
        y += (i + i2);    
        System.out.print(y);  
    }  
    public int method(int i) {    
        y += i;    
        return  y;  
    }  
    public static void main(String[] args) {    
        new MyClass(new MyClass(5).method(2), 4);  
    }
}


  • A. This program writes "12" to the standard output.

  • B. This program writes "24" to the standard output.

  • C. This program writes "21" to the standard output.

  • D. This program writes "17" to the standard output.

  • E. This program writes "18" to the standard output.

  • F. This program writes "16" to the standard output.

The correct answer and its explanation will be included in the next quiz in two weeks! For more Java quizzes, puzzles, and assignments, take a look at my site!

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
java ,constructor ,parameter passing ,quiz

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}