Writing Methods

AP Computer Science A· difficulty 2/5

public class K {
    private int n;
    public K(int n) { this.n = n; }
    public String toString() { return "K(" + n + ")"; }
}
// ...
K k = new K(7);
System.out.println("Got " + k);

What is printed?

  • A

    Got K(7)

    check_circle
  • B

    Compile-time error

  • C

    Got 7

  • D

    Got K

Explanation

String concatenation invokes toString on the object, producing "Got K(7)".

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

Related questions