What is the result?

Given the fragment:

int [] array = {1, 2, 3, 4, 5};
System.arraycopy (array, 2, array, 1, 2);
System.out.print (array [1]);
System.out.print (array[4]);

What is the result?

Given the fragment:

int [] array = {1, 2, 3, 4, 5};
System.arraycopy (array, 2, array, 1, 2);
System.out.print (array [1]);
System.out.print (array[4]);

What is the result?

A.
14

B.
15

C.
24

D.
25

E.
34

F.
35

Explanation:
The two elements 3 and 4 (starting from position with index 2) are copied into position index 1 and 2 in the same array.
After the arraycopy command the array looks like:
{1, 3, 4, 4, 5};
Then element with index 1 is printed: 3
Then element with index 4 is printed: 5
Note: The System class has an arraycopy method that you can use to efficiently copy data from one array into another:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.



Leave a Reply 4

Your email address will not be published. Required fields are marked *


James

James

The Answer is F.

The statement:

System.arraycopy(array, 2, array, 1, 2);

copies the elements array[2] and array[3] to positions array[1] and array[2] to give the new array:

{1, 3, 4, 4, 5}

Now, array[1] = 3, and array[4] = 5.