Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Suppose that we have the two classes below. Trace the execution of the main p

ID: 3573572 • Letter: 1

Question

1.      Suppose that we have the two classes below. Trace the execution of the main program in the Driver class.

public class Driver {

      public static void main(String[] args) {

            FakeArrayList first = new FakeArrayList(3);

            first.set(2, 'a');

            first.set(1, 'b');

            FakeArrayList second = new FakeArrayList(5);

            second.set(4, 'c');

            second.set(1, 'd');

      }

}

public class FakeArrayList {

      private int size;

      private char[] data;

      public FakeArrayList(int capacity) {

            data = new char[capacity];

            size = 0;

      }

      public int getSize() {

            return size;

      }

      public char get(int index) {

            return data[index];

      }

      public void set(int index, char value) {

            data[index] = value;

      }

}

Main Stack Frame

Identifier

Address

Contents

100

101

102

103

104

Heap

Identifier

Address

Contents

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

Main Stack Frame

Identifier

Address

Contents

100

101

102

103

104

Explanation / Answer

public class Driver {

      public static void main(String[] args) {
          
           System.out.println(Thread.currentThread().getStackTrace());
            FakeArrayList first = new FakeArrayList(3);
           System.out.println(Thread.currentThread().getStackTrace());
            first.set(2, 'a');
           System.out.println(Thread.currentThread().getStackTrace());
            first.set(1, 'b');
           System.out.println(Thread.currentThread().getStackTrace());
            FakeArrayList second = new FakeArrayList(5);
           System.out.println(Thread.currentThread().getStackTrace());
            second.set(4, 'c');
           System.out.println(Thread.currentThread().getStackTrace());
            second.set(1, 'd');
           System.out.println(Thread.currentThread().getStackTrace());
      }

}

public class FakeArrayList {

      private int size;

      private char[] data;

      public FakeArrayList(int capacity) {

            data = new char[capacity];

            size = 0;

      }

      public int getSize() {

            return size;

      }

      public char get(int index) {

            return data[index];

      }

      public void set(int index, char value) {

            data[index] = value;

      }

}