0

If I write out an array the long way in a seperate class such as

public Student [] getArray(){
    Student [] studentArray = new Student[3];
    studentArray[0] = new Student (”Mel”);
    studentArray[1] = new Student (”Jared”);
    studentArray[2] = new Student (”Mikey”);
    return studentArray;
}

Will the return statement return all the names to my other class that I'm actually going to run, or just one?

4 Answers 4

2

Here, the return statement will return the entire array, which means that the caller can access all three of the Student objects. For example:

Student[] arr = getArray();
System.out.println(arr[0]); // Prints out Mel student
System.out.println(arr[1]); // Prints out Jared student
System.out.println(arr[2]); // Prints out Mikey student

If you want to return just one Student, then your return type would be Student and you would have to specifically pick which one to return. In Java, returning an array always returns the entire array, and you don't need to say that you're returning all of the contents with it.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

Of course all the names. It returns your array which contains all your created Students.
I guess youre new to programming. So read this to know what are arrays and how to use them.

Comments

0

This statement

Student[] studentArray = new Student[3];

creates a new array, capable of holding three references to Student instances and assigns the reference to this array to the local variable studentArray

return studentArray;

returns the reference to this array to the caller of the method. He can use this array reference to get the references of the Student objects.

He can either store it in another variable or use it directly:

Student[] callersArray = getArray();
System.out.println(callersArray[0]);  // will print a Student "Mel"

System.out.println(getArray()[0]);    // will print another(!) Student "Mel"

Comments

0

All values of the array are returned. You can write it shorter:

public Student [] getArray(){
  return new Student[]{new Student (”Mel”), new Student (”Jared”), new Student (”Jared”)};
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.