In the code snippet below we are going to learn how to use the System.arraycopy()
method to copy array values. This method will copy array from the specified source array, starting from the element specified by starting position. The array values will be copied to the target array, placed at the specified start position in the target array and will copy values for the specified number of elements.
The code snippet below will copy 3 elements from the letters
array and place it in the results
array. The copy start from the third elements which is the letter U
and will be place at the beginning of the target
array.
package org.kodejava.lang;
public class ArrayCopy {
public static void main(String[] args) {
// Creates letters array with 5 chars inside it.
String[] letters = {"A", "I", "U", "E", "O"};
// Create an array to where we are going to copy
// some elements of the previous array.
String[] results = new String[3];
// Copy 3 characters from letters starting from the
// third element and put it inside result array
// beginning at the first element
System.arraycopy(letters, 2, results, 0, 3);
// Just print out what were got copied, it will
// contains U, E, and O
for (String result : results) {
System.out.println("result = " + result);
}
}
}
The output of the code snippet:
result = U
result = E
result = O
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024