Arrays of Objects

 

  1. What is the output of the following program? (Trace it first by hand and then cut and paste it into java to see if you are right.)

  2. Why is new used twice? (For the array and for the box)

  3. What is in a ‘box’ object?

  4.  How many strings are in an array of 5 box objects?

 

public class riddle1

{

 

    public static void main (String args [])

    {

        System.out.println ("How do you catch a unique rabbit?");

        box array [] = new box [5];

        for (int i = 0 ; i < 5 ; i++)

        {

            array [i] = new box ();

            array [i].p = "U";

            array [i].s = "I";

            array [i].c = " ";

        }

        array [0].c = array [0].s;

        array [3].s = "N";

        array [0].c = array [3].s;

        array [2].c = array [2].p;

        array [3].c = array [0].p;

        array [2].p = array [1].s;

        array [4].s = "T";

        array [1].p = "P";

        array [3].c = "O";

        array [2].s = array [1].p;

        array [4].p = array [1].c;

        array [1].p = "Q";

        array [3].p = array [1].c;

        array [4].c = array [0].s;

        array [1].c = array [2].c;

        array [1].s = "E";

        array [2].p = array [3].p;

 

        for (int i = 0 ; i < 5 ; i++)

            System.out.print (array [i].p + array [i].c + array [i].s);

    }

}

 

public class box

{

    String s;

    String p;

    String c;

}