Search code examples
javaarraysvariablesreference

Problem with: Reference Variable and while loop question


So about two weeks ago I decided that I was going to dive in and finally learn a programming language. Of course I am here because I chose Java. Aside from numerous online resources, I also purchased Head First Java, which I think has been really amazing at explaining concepts. I have to admit some of the assignments it give are really difficult for a beginner, but I have been managing up until now. Can someone please tell me what is going on here? The assignment is to determine which of the reference variable refer to which objects. Not all reference variables will be used.

class HeapQuiz {

     int id = 0;

     public static void main (String [] args) {
       int x = 0;
       HeapQuiz [] hq = new HeapQuiz[5];
       while ( x < 3) {
           hq[x] = new HeapQuiz();
           hq[x].id = x;
           x = x + 1;
     }

     hq[3] = hq[1];
     hq[4] = hq[1];
     hq[3] = null;
     hq[4] = hq[0];
     hq[0] = hq[3];
     hq[3] = hq[2];
     hq[2] = hq[0];
  }
}

Here are the answers...

hq[1] -----> id = 1
hq[3] -----> id = 2
hq[4] -----> id = 0

I understand that an array is created. I think I understand the hq[x] represents the the array positions, but how is x being assigned? How does the JVM progress through the loop? The answers are posted above, but I have not idea how the loop is producing those answers. More specifically, how is hq[1] referring to id = 1 and how is hq[3] referring to id = 2 and so forth. Any help is greatly appreciated. Thanks in advance.

The Noobiest of all Noobs


Solution

  • First it creates 3 objects in the while loop:

    hq[0] --> id = 0
    hq[1] --> id = 1
    hq[2] --> id = 2
    

    Then shuffles things around:

    hq[3] = hq[1];   // hq[3].id = 1
    hq[4] = hq[1];   // hq[4].id = 1
    hq[3] = null;    // null
    hq[4] = hq[0];   // hq[4].id = 0
    hq[0] = hq[3];   // null
    hq[3] = hq[2];   // hq[3].id = 2
    hq[2] = hq[0];   // null
    

    So you end up with:

    hq[0] --> null
    hq[1] --> id = 1
    hq[2] --> null
    hq[3] --> id = 2
    hq[4] --> id = 0