112k views
4 votes
Write a method in java that takes an int array, a starting index, and an ending index. Return a copy of the array that just has the elements from the starting index to the ending index. Display each of the values in the returned array (outside of the method)

User Mhaken
by
8.4k points

1 Answer

3 votes

Final answer:

To create a method in Java that returns a copy of an int array, use the arraycopy() method from the System class. Display each value in the returned array by iterating through it and printing each element.

Step-by-step explanation:

To create a method in Java that returns a copy of an int array, you can use the arraycopy() method from the System class. Here is an example:

public static int[] copyArray(int[] arr, int startIndex, int endIndex) {
int length = endIndex - startIndex + 1;
int[] copy = new int[length];
System.arraycopy(arr, startIndex, copy, 0, length);
return copy;
}

After creating this method, you can display each value in the returned array by iterating through it and printing each element. Here is an example:

int[] arr = {1, 2, 3, 4, 5};
int[] copy = copyArray(arr, 1, 3);
for (int num : copy) {
System.out.println(num);
}

User Ignat Insarov
by
8.1k points