How many objects have been created when the line / / do complex stuff is reached?

Given: How many objects have been created when the line / / do complex stuff is reached?

Given: How many objects have been created when the line / / do complex stuff is reached?

A.
Two

B.
Three

C.
Four

D.
Six



Leave a Reply 4

Your email address will not be published. Required fields are marked *


renko

renko

?? A?

If we use the default Dog-constructor:
public class Dog {
/*Dog() {
Try {
throw new Exception();
} //catch (Exception e) {}

}*/
}
public class Test {

public static void main(String[] args) {
Dog d1 = new Dog();
Dog d2 = new Dog();
Dog d3 = d2;
// do complex stuff
System.out.println(“d1: “+d1.toString());
System.out.println(“d2: “+d2.toString());
System.out.println(“d3: “+d3.toString());

}

}
Output:
d1: Dog@15db9742
d2: Dog@6d06d69c
d3: Dog@6d06d69c

Kunal

Kunal

You are right. Correct answer is 2. It’s clearly visibble that d3 is nothing but just assignment of object memory reference.

Correct answer is 2.

Sucuk

Sucuk

“The 13th and 14th line of the program all create a Dog object. When creating objects Dog, will perform the third line constructor and a TRY- CATCH establish and throw in the new Exception objects. So every time a Dog object is created, two objects are actually created. Two Dog objects are created and four objects are created.”

I got this explanation from Magiclen.org, they claim the answer is four. Does anybody understand what they mean with this explanation??

Job van den Berg

Job van den Berg

In this example, everytime the ‘new’ keyword is used, a new object will be created.

An Exception actually extends the Throwable, which extends the Object (1), therefore creating(or throwing) a ‘new Exception();’ creates a new object.

Two Dog objects are created, which themselves also create a new object. (C) Four is the correct anwser.

(1) https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html