🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Java Classes and Objects: all 10 questions

Quiz: Java Classes and Objects · Question 8 of 10

What does this print? (code)

What does this print?

class Pen {
    String color;
    Pen(String color) { this.color = color; }
    @Override
    public String toString() { return "Pen(" + color + ")"; }
}
public class Main {
    public static void main(String[] args) {
        Pen p = new Pen("blue");
        System.out.println(p + " " + p.color.length());
    }
}
  1. A.Pen@1b6d3586 4
  2. B.blue 4
  3. C.Pen(blue) 5
  4. D.Pen(blue) 4
Answer & explanation

Correct answer: Pen(blue) 4

String joining calls the overridden toString(); "blue" has 4 characters.

Can you get the rest right without peeking?

Take the timed Quiz: Java Classes and Objects quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →