Java SE 8 Programmer II Exam Question

Java SE 8 Programmer II Exam Question

Question

Given: public class Customer{ private String fName; private String lName; private static int count; public customer (String first, String last) {fName = first, lName = last; ++count;} static{count = 0;} public static int getCount(){return count; } } public class App{ public static void main (String [] args){ Customer c1 = new Customer("Larry", "Smith"); Customer c2 = new Customer("Pedro", "Gonzales"); Customer c3 = new Customer("Penny", "Jones"); Customer c4 = new Customer("Lars", "Svenson"); c4 = null; c3 = c2; System.out.println (Customer.getCount()); } } What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D. E.

D.

The given code defines two classes: Customer and App.

The Customer class has three instance variables: fName and lName of type String, and count of type int. fName and lName are used to store the first and last name of a customer, while count keeps track of the number of Customer objects that have been created.

The Customer class has a constructor that takes two parameters, first and last. This constructor initializes the fName and lName instance variables with the values of the first and last parameters, respectively. It also increments the count variable by 1.

The Customer class has a static block that initializes the count variable to 0. This block is executed only once, when the class is loaded.

The Customer class has a static method getCount() that returns the current value of the count variable.

The App class has a main method that creates four Customer objects (c1, c2, c3, and c4) with different first and last names. The main method then sets c4 to null and sets c3 to c2. Finally, it prints the result of calling the getCount() method on the Customer class.

When the main method is executed, it creates four Customer objects (c1, c2, c3, and c4). Each time a Customer object is created, the count variable is incremented by 1. So after the four Customer objects are created, the value of count is 4.

When c4 is set to null, the reference to the Customer object it was pointing to is lost, but the object itself still exists in memory. However, since there are no references to it, it becomes eligible for garbage collection.

When c3 is set to c2, both c2 and c3 now refer to the same Customer object. The Customer object that c3 was previously referring to is no longer referenced by any variable, so it becomes eligible for garbage collection.

Finally, the main method calls the getCount() method on the Customer class, which returns the value of the count variable. Since the value of count is 4, the output of the program is 4.

Therefore, the correct answer is D. 4.