Printing out all the objects in array list [duplicate] Printing out all the objects in array list [duplicate] arrays arrays

Printing out all the objects in array list [duplicate]


Override toString() method in Student class as below:

   @Override   public String toString() {        return ("StudentName:"+this.getStudentName()+                    " Student No: "+ this.getStudentNo() +                    " Email: "+ this.getEmail() +                    " Year : " + this.getYear());   }


Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Overridepublic String toString() {    return "Student No: " + this.getStudentNo() +            ", Student Name: " + this.getStudentName();}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();// You can directly print your ArrayListSystem.out.println(students); // Or, iterate through it to print each instancefor(Student student: students) {    System.out.println(student);  // Will invoke overrided `toString()` method}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.


You have to define public String toString() method in your Student class. For example:

public String toString() {  return "Student: " + studentName + ", " + studentNo;}