How can we copy one array from another in Java

Java 8Object Oriented ProgrammingProgramming

Let us first create a string array −

String[] arr = new String[] { "P","Q", "R", "S", "T"};

Now, calculate the length of the above array and create a new array with the same length −

int len = arr.length;
String[] arr2 = new String[len];

Let us copy one array from another −

System.arraycopy(arr, 0, arr2, 0, arr.length);

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String[] arr = new String[] { "P","Q", "R", "S", "T"};
      System.out.println("Initial array...");
      for (int i = 0; i < arr.length; i++)
      System.out.println(arr[i]);
      int len = arr.length;
      String[] arr2 = new String[len];
      System.arraycopy(arr, 0, arr2, 0, arr.length);
      System.out.println("New array...copied");
      for (int i = 0; i < arr2.length; i++)
      System.out.println(arr2[i]);
   }
}

Output

Initial array...
P
Q
R
S
T
New array...copied
P
Q
R
S
T
raja
Published on 23-Apr-2019 16:16:33
Advertisements