user724198
user724198

Reputation:

Passing multi-dimensional arrays

I wrote the following code. It works great, but I have a question (so I don't bomb any future additions). Here's the code:

public class MoreStuff extends javax.swing.JFrame {

// Globals
int quiz[][]; // Used for Quiz subroutines


...


private void btnGetQuizActionPerformed(java.awt.event.ActionEvent evt) {                                           

    Functions fns = new Functions(); 
    String strout;
    int i = 0;

    // Get the quiz
    quiz = fns.GetQuiz();

The fns.GetQuiz() returns a 2-dimensional array perfectly.

My question is this: Having declared a multidimensional array at the class level, when the computer executes quiz = fns.GetQuiz, have I passed an object or have I only copied a reference?

Upvotes: 1

Views: 64

Answers (2)

sstan
sstan

Reputation: 36513

Let's say GetQuiz()'s implementation is simply:

public int[][] GetQuiz() {
    int[][] someArray = new int[10][];
    return someArray;
}

The line int[][] someArray = new int[10][]; allocates an array on the heap and assigns a reference to that object to someArray.

When the method GetQuiz() finishes executing, the only thing "destroyed" is someArray, which is simply the reference to the array. The array itself lives on the heap, and only becomes eligible for garbage collection once there are no more references to the array.

In your example, because a copy of the reference is assigned to the quiz variable, even when someArray is destroyed, you still have quiz's reference pointing to the array, so the garbage collector will not try to destroy the array.

I think you might find the information in this thread helpful: Stack and Heap memory in Java.

Upvotes: 2

Alexander
Alexander

Reputation: 490

In your program, quiz will hold its value even after the execution of btnGetQuizActionPerformed() because it receives a copy of the reference tofns.

Upvotes: 0

Related Questions