113k views
3 votes
Questions 5 - 7 refer to the following code: public class Whatchamacallit { private double price; private String title; public Whatchamacallit() { this (0, "none"); } public Whatchamacallit(double p, String t) { price = 0; if (p > 0) { price = p; } title = t; } public String toString() { return title + " costs $" + price; } } The following code segment appears in another class: ArrayList list = new ArrayList(); list.add(new Whatchamacallit()); list.add(new Whatchamacallit(3.5, "book")); list.add(new Whatchamacallit(-17, "CD")); list.add(new Whatchamacallit(18.95, "sweater")); list.add(new Whatchamacallit(5, "notebook")); /* Missing Code */ Suppose the following line is used to replace /* Missing Code */. System.out.println(list.get(0)); What is printed as a result of executing the code segment?

1 Answer

2 votes
Some code formatting is required to understand this question

Whatchamacallit {
private double price;
private String title;
public Whatchamacallit()
{
this (0, "none");
}
public Whatchamacallit(double p, String t)
{
price = 0;
if (p > 0)
{
price = p;
}
title = t;
}
public String toString()
{ return title + " costs $" + price; }
}

The following code segment appears in another class:

ArrayList list = new ArrayList();
list.add(new Whatchamacallit());
list.add(new Whatchamacallit(3.5, "book"));
list.add(new Whatchamacallit(-17, "CD"));
list.add(new Whatchamacallit(18.95, "sweater"));
list.add(new Whatchamacallit(5, "notebook"));
/* Missing Code */
Suppose the following line is used to replace /* Missing Code */. System.out.println(list.get(0));

The answer is 'none costs $0'

This is because the line:
'System.out.println(list.get(0))'
gets the first item (index 0) in the array, which was :
'list.add(new Whatchamacallit()) '
and Whatchamacallit() sets price = 0 and title = 'none' in the class Whatchamacallit

The specific output of the 'get(0)' is because of the 'toString()' method in
Whatchamacallit

User Dainius
by
7.0k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.