Let's say I've an array:
int[] array = new int[] {0,1,2,3,4,5,6,7,8,9};
I want to print a sub-array of the above array starting from index i
and ending at index j
. For example, if i=3 & j=6, the sub-array to be printed would be:
[3, 4, 5, 6]
or simply as 3 4 5 6
We can simply print the sub-array with a for loop as:
for (int k=i; k<=j; k++) System.out.print(array[k]+" ");
But I'm looking for a method to achieve this like Arrays toString()
method.
So, we can use Arrays.copyOfRange() to create a copy of the desired sub-array and print it as:
int[] subArray1 = Arrays.copyOfRange(array, i, j+1);
System.out.println(Arrays.toString(subArray1));
There are few other ways to achieve this as well but all of them tend to use extra space to create a copy of the sub-array. Is there any method or way (except the above) to directly print the sub-arrays from the given indices without using extra memory?