101k views
2 votes
Consider the following class definition.

public class Contact
{
private String contactName;
private String contactNumber;
public Contact(String name, String number)
{
contactName = name;
contactNumber = number;
}
public void doSomething()
{
System.out.println(this);
}
public String toString()
{
return contactName + " " + contactNumber;
}
}
The following code segment appears in another class.
Contact c = new Contact("Alice", "555-1234");
c.doSomething();
c = new Contact("Daryl", "");
c.doSomething();
What is printed as a result of executing the code segment?"
A Daryl
B Daryl 555-1234
C Alice 555-1234 Daryl
D Alice 555-1234 Daryl 555-1234
E this this

User Ali Padida
by
8.5k points

1 Answer

7 votes

Final answer:

The code segment creates two objects of the Contact class. The first object's output is "Alice 555-1234" and the second object's output is "Daryl".

Step-by-step explanation:

The code segment creates two objects of the Contact class. The first object has the contactName set to "Alice" and the contactNumber set to "555-1234". When the doSomething() method is called on this object, it prints the result of the toString() method, which combines the contactName and contactNumber. So, the output of the first c.doSomething() statement is "Alice 555-1234".

The second object has the contactName set to "Daryl" and the contactNumber set to an empty string. When the doSomething() method is called on this object, it also prints the result of the toString() method, which combines the contactName and contactNumber. In this case, the contactNumber is an empty string, so it is not displayed in the output. So, the output of the second c.doSomething() statement is "Daryl".

User Aseem Kishore
by
8.5k points