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

Programming Language is JAVA: a) What are the contents of a1 and a2 after the co

ID: 3830751 • Letter: P

Question

Programming Language is JAVA:

a) What are the contents of a1 and a2 after the code below executes?

int [] a1 = new int[5];

for (int i = 0; i < a1.length; i++) a1[i] = i+1;

int [] a2 = a1;

a1[0] = a2[1];

a2[2] = a2[0];

b) Write a method void copyArray(int [] source, int [] destination) that copies the items of source into destination. If destination is longer than source then pad the remaining elements with 0's. If destination is shorter than source then just copy the first destination.length elements.

Explanation / Answer

a) What are the contents of a1 and a2 after the code below executes?

Answer: Both will have same contents

a1 = [2, 2, 2, 4, 5]
a2 = [2, 2, 2, 4, 5]

Question b

public static void copyArray(int [] source, int [] destination) {
       int i=0;
       int length;
       int diff = 0;
       if(destination.length> source.length){
           length= source.length;
           diff= destination.length- source.length;
       }
       else{
           length=destination.length;
       }
       for( i=0; i<length; i++){
           destination[i]=source[i];
       }
       for( i=0; i<diff; i++){
           destination[i]=0;
       }
   }