Home > Net >  Unable to get array data (Using Variable Arguments)
Unable to get array data (Using Variable Arguments)

Time:04-19

Im trying to make an array of objects and when i try to fetch the corresponding subjects of a student it shows some code(not error/exception). Below Ive attached the code.

class student{

private String roll;
private String name;
private String dept;
private String[] subjects;
    
public student(String roll, String name, String dept, String ...subjects) {
    
    this.roll=roll;
    this.name=name;
    this.dept=dept;
    this.subjects=subjects;
}

public String getRoll() {
    return roll;
}

public void setRoll(String roll) {
    this.roll = roll;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDept() {
    return dept;
}

public void setDept(String dept) {
    this.dept = dept;
}

public String[] getSubjects() {
    return subjects;
}

public void setSubjects(String ...subjects) {
    this.subjects = subjects;
}

public String toString() {
    return roll " " name " " dept " " subjects;
}

}

public class practice {

public static void main(String[] args) {
    
    student []s = new student[1];
    
    s[0] = new student("1","kamal","CS","Math","Science","Physics");
    
    for(student x:s) {
        System.out.println(x);
    }

}

}

This is the output, I am getting: 1 kamal CS [Ljava.lang.String;@2be94b0f

CodePudding user response:

You need to override toString()

CodePudding user response:

Can't comment @Julian answer, but he is right (and the first). To be more precise, when you call System.out.println with an Object inside, the jvm will call the toString method of this object. By default it print out the class of the object and the "unsigned hexadecimal representation of the hash code of the object". (https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString--) This explain why you are seeing this strange string, and why you should override the toString method.

  • Related