toString() Method
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 41 of 87.
Every class in Java inherits from the Object class, which provides several useful methods. One of the most commonly overridden is toString(), which returns a string representation of an object.
By default, toString() returns the class name followed by the object's hash code, which isn't very helpful:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Person p = new Person("Alice", 25);
System.out.println(p); // Person@15db9742By overriding toString(), you can provide meaningful output that describes the object's state:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}
Person p = new Person("Alice", 25);
System.out.println(p); // Person[name=Alice, age=25]The toString() method is called automatically when you print an object or concatenate it with a string. This makes debugging much easier since you can quickly see an object's contents without writing extra code.
Challenge
EasyLet's build a product inventory system that displays meaningful information about items using custom toString() implementations. You'll create a Product class that overrides the default toString() method to provide a clear, readable representation of each product.
You'll organize your code across two files:
Product.java: Create a class representing an inventory item. Each Product has three private fields:name(String),price(double), andquantity(int). Include a constructor that initializes all three fields. Override thetoString()method to return a formatted string in this exact format:Product[name=X, price=Y, quantity=Z]where X, Y, and Z are the actual field values. The price should display as a plain number (no special formatting needed).Main.java: Bring your Product class to life by creating and displaying products. You'll receive three inputs: a product name (String), a price (double), and a quantity (int). Create a Product with these values, then simply print the product object directly usingSystem.out.println(). Thanks to your overriddentoString()method, this will automatically display the formatted product information instead of the cryptic default output!
You will receive three inputs: the product name (String), the price (double), and the quantity (int).
Notice how printing the object directly calls your toString() method automatically—this is what makes debugging and logging so much easier in real applications!
Cheat sheet
Every class in Java inherits from the Object class. The toString() method returns a string representation of an object.
By default, toString() returns the class name followed by the object's hash code:
Person p = new Person("Alice", 25);
System.out.println(p); // Person@15db9742Override toString() to provide meaningful output:
@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
Person p = new Person("Alice", 25);
System.out.println(p); // Person[name=Alice, age=25]The toString() method is called automatically when you print an object or concatenate it with a string.
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String name = scanner.nextLine();
double price = scanner.nextDouble();
int quantity = scanner.nextInt();
// TODO: Create a Product object with the input values
// TODO: Print the product object directly
// (This will automatically call your toString() method!)
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System