0

I want to print out the values of an array in a "for statement", but instead, it's printing the object address.

        Person student = new Person();
        Person [] students = new Person[10];
        students[0] = student;
        students[1] = student;
        students[2] = student;

        students[0].studentDetails("Abel Morris Ben", "Java Programming", 99);
        students[1].studentDetails("Jane Doe", "Web Development", 85);
        students[2].studentDetails("John Doe", "Ethical Hacking", 80);


        for( int i=0; i <= 2; i++) {

            System.out.println(students[i]);
        }

It's is printing the object location instead:

Person@2a139a55
Person@2a139a55
Person@2a139a55
skomisa
  • 16,436
  • 7
  • 61
  • 102
Abel Ben
  • 13
  • 3

1 Answers1

0

please try below given code.

public class Person {

    private String name;
    private String designation;
    private int salary;

    public void studentDetails(String name, String designation, int salary) {
        this.name = name;
        this.designation = designation;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public String getDesignation() {
        return designation;
    }

    public int getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", designation=" + designation + ", salary=" + salary + "]";
    }

    public static void main(String[] args) {
        Person student = new Person();
        Person[] students = new Person[10];
        students[0] = student;
        students[1] = student;
        students[2] = student;

        students[0].studentDetails("Abel Morris Ben", "Java Programming", 99);
        students[1].studentDetails("Jane Doe", "Web Development", 85);
        students[2].studentDetails("John Doe", "Ethical Hacking", 80);

        for (int i = 0; i <= 2; i++) {
            System.out.println(students[i]);
        }
    }
}
Arun Kumar
  • 340
  • 2
  • 15