Copying Arrays Using copyOfRange() method

We can also use the copyOfRange() method defined in Java Arrays class to copy arrays. For example,


\begin{lstlisting}
// To use toString() and copyOfRange() method
import java.uti...
...tln(''destination2 = '' + Arrays.toString(destination2));
}
}
\end{lstlisting}

Output for the above code block will be


\begin{lstlisting}
destination1 = [2, 3, 12, 4, 12, -2]
destination2 = [12, 4, 12]
\end{lstlisting}

In the above example, notice the line,


\begin{lstlisting}
int[] destination1 = Arrays.copyOfRange(source, 0, source.length);
\end{lstlisting}

Here, we can see that we are creating the destination1 array and copying the source array to it at the same time. We are not creating the destination1 array before calling the copyOfRange() method.