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

Java Quiz 6: Calling Constructors by Using the Keyword This

DZone's Guide to

Java Quiz 6: Calling Constructors by Using the Keyword This

Catch up with the answer to the last Java Puzzle about static variables and object instantiation and dive into a new one about calling constructors with the this keyword.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Before we start with this week's quiz, here is the answer to Java Puzzle 5: Static Variables and Object Instantiation.

  1. We actually need to invoke the method intMethod to assign a value to the variable i and invoke the strMethod to assign a value to the object str.

  2. By instantiating the class MyClass, we can create an object. At the same time, we assign a value to the variable i2.

  3. By creating objects, the statement System.out.print(i2); writes the value of i2 to the standard output. That is unwanted in some cases. Therefore, we invoke the methods as follows:

  4. MyClass mc = new MyClass(new MyClass("", 0, 3).strMethod("y"), new MyClass("", 0, 3).intMethod(9), 8);


  5. By adding the previous statement at line 29, the output of the program becomes y98.

Here is the quiz for today!

What happens when the following program is compiled and run?

public class MyClass {
    String str = "";
    String str2 = "";

    MyClass() {
        this("z");
        System.out.print(str + str2);
    }
    MyClass(String str) {
        this("x", "y");
        this.str += str;
        System.out.print(this.str + str2);
    }
    MyClass(String str, String str2) {
        this.str += str;
        this.str2 += str2;
        System.out.print(this.str + this.str2);
    }
    public static void main(String[] args) {
        MyClass mc = new MyClass();
    }
}


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

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

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

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

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

  • F. This program writes nothing 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!

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,quiz ,constructor ,constructor chaining

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}