Writing Methods

AP Computer Science A· difficulty 3/5

public class Coin {
    private String side;
    public Coin(String s) { side = s; }
    public String toString() { return "Coin: " + side; }
}
// ...
Coin c = new Coin("Heads");
System.out.println(c);

What is printed?

  • A

    Compile-time error

  • B

    Coin@<hash>

  • C

    Heads

  • D

    Coin: Heads

    check_circle

Explanation

println implicitly calls toString on the object, returning "Coin: Heads".

Want 10 more like this — adaptive to your weak spots?

Related questions