AP® Computer Science A glossary
toString
Also called: toString method
Course: AP® Computer Science A Shows up in: Unit 1: Using Objects and Methods
A method that returns a String representing an object; println and string concatenation call it automatically.
Appears in the course and exam description (CED): 1.15.A.5
Every class inherits a toString method. Classes often provide their own so printing an object shows useful text. Overriding toString is outside the AP® exam, but you will read it in class code.
public class Book
{
private String title;
public Book(String t)
{
title = t;
}
public String toString()
{
return "Book: " + title;
}
public static void main(String[] args)
{
System.out.println(new Book("Tides"));
}
}
Output:
Book: Tides Learn it properly, with a checkpoint 3.3 Anatomy of a Class