[java] Printing out all the objects in array list

I need to be able to print out the Student objects(all variables) in my array list. Is this possible? When i try to print it outputs this sort of thing e.g student.Student@82701e. I think it's hexadecimal or something

This is my code:

package student;

public class Student {

    private String studentName;
    private String studentNo;
    private String email;
    private int year;


    public Student() {
        this.studentName = null;
        this.studentNo = null;
        this.email = null;
        this.year = -1;
    }

    public Student(String nName, String nNum, String nEmail, int nYr) {
        this.studentName = nName;
        this.studentNo = nNum;
        this.email = nEmail;
        this.year = nYr;
    }

    public void setStudentName(String newStudentName) {
        this.studentName = newStudentName;
    }

    public void setStudentNo(String newStudentNo) {
        this.studentNo = newStudentNo;
    }

    public void setEmail(String newEmail) {
        this.email = newEmail;
    }

    public void setYear(int newYear) {
        this.year = newYear;
    }

    public String getStudentName() {
        return studentName;
    }

    public String getStudentNo() {
        return studentNo;
    }

    public String getEmail() {
        return email;
    }

    public int getYear() {
        return year;
    }
}

package student;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class studentTest {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);



        List<Student> Students = new ArrayList();


        Student student1 = new Student();

        student1.setStudentName("Bob Marley");
        student1.setStudentNo("N0002");
        student1.setEmail("[email protected]");
        student1.setYear(2);

        Students.add(student1);

        Student student2 = new Student();

        student2.setStudentName("Bill Harvey");
        student2.setStudentNo("N0003");
        student2.setEmail("[email protected]");
        student2.setYear(2);

        Students.add(student2);

        Student student3 = new Student();

        student3.setStudentName("John Beans");
        student3.setStudentNo("N0004");
        student3.setEmail("[email protected]");
        student3.setYear(2);

        Students.add(student3);


        System.out.println("Add new students: ");
        System.out.println("Enter number of students to add: ");
        int countStudents = input.nextInt();

        for (int i = 0; i < countStudents; i++) {
            Student newStudents = new Student();


            System.out.println("Enter details for student: " + (i + 1));

            System.out.println("Enter name: ");
            newStudents.setStudentName(input.next());

            System.out.println("Enter Number: ");
            newStudents.setStudentNo(input.next());System.out.println("Search by student number: ");



            System.out.println("Enter email: ");
            newStudents.setEmail(input.next());

            System.out.println("Enter year: ");
            newStudents.setYear(input.nextInt());
            Students.add(newStudents);
        }


    }
}

This question is related to java arrays printing arraylist

The answer is


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: -

@Override
public 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 ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(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;
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to printing

How do I print colored output with Python 3? Print a div content using Jquery Python 3 print without parenthesis How to find integer array size in java Differences Between vbLf, vbCrLf & vbCr Constants Printing variables in Python 3.4 Show DataFrame as table in iPython Notebook Removing display of row names from data frame Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window Print a div using javascript in angularJS single page application

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable