How to override toString method to print contents of a object in Java

Java example to override toString method to print contents of an object :

To print the contents of an object, we need to override toString() method of that object. In this tutorial we will learn how to override toString() method of an object and what are the benifits of doing it.

Example :

We have two class and Inside we will create an arraylist to contain few Student objects. Then we will iterate the list and print out the object values. Following are the classes :

public class Student {
    //student name
    private String studentName;

    //marks of the student
    private int studentMarks;

     * Constructor to create a Student object
     * @param name  : Name of the student
     * @param marks : Marks of the student
    public Student(String name, int marks) {
        this.studentName = name;
        this.studentMarks = marks;

    public String toString() {
        return "Marks for " + studentName + " is " + studentMarks;

1. studentName variable contains the name of the student.
2. studentMarks variable contains the marks of the student.
3. public Student(String name, int marks) is the constructor to create one Student object. We will pass the name and age of the student and save it in the object in studentName and studentMarks variables.
4. We are overriding the toString() method in this class and the return String is the combination of studentName and studentMarks.

Now, let’s take a look into the class :

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        ArrayList studentList = new ArrayList();

        studentList.add(new Student("Alex",35));
        studentList.add(new Student("Bryan",45));
        studentList.add(new Student("Andy",58));
        studentList.add(new Student("Jane",95));
        studentList.add(new Student("Lily",77));

        for(Student s : studentList){


1. First we have created one ArrayList studentList that can hold objects of type Student.
2. Next, we added five different Student objects with different name and age.
3. Using a for loop, we have printout the objects. Note that we are directly passing the object to the System.out.println() .

Output :

The above program will print the below output:

Marks for Alex is 35
Marks for Bryan is 45
Marks for Andy is 58
Marks for Jane is 95
Marks for Lily is 77

So, the program print out the same output we have returned from the override toString() method.

Leave a Reply