Question 1701
public class Money
{
private int cents;
public Money(int c) { cents = c; }
public String toString()
{
return "$" + (cents / 100) + "." + (cents % 100);
}
}
Consider the following code segment.
Money m = new Money(2507);
System.out.println("price: " + m);
What is printed when the code segment executes?Main Solution
Answer
Answer: D. When an object appears in a string concatenation, Java implicitly calls its toString() method. 2507 / 100 = 25 and 2507 % 100 = 7, so the string built by toString is "$25.7" (no zero-padding because the modulus is the literal integer 7). The full output is "price: $25.7". Option B is what a properly formatted accountant would want — and is therefore the most tempting wrong answer — but the code does not zero-pad. Option A would only happen if toString were not overridden.
Answer: Correct: D
A
A reference address is printed for m.
B
price: $25.07
C
price: 2507
D
price: $25.7
Answer images

