Copying part of Array in Java Example

This Java example shows how to copy part of an Array in Java Arrays.copyOf() method.

Copying part of Array in Java Example

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {

      // intializing an array arr1
      long[] arr1 = new long[] {15, 10, 45};

      // printing the array
      System.out.println("Printing 1st array:");
      for (int i = 0; i < arr1.length; i++){
         System.out.print(arr1[i]+" ");  
      }
      
      System.out.println("");  

      // copying array arr1 to arr2 with newlength as 5
      long[] arr2 = Arrays.copyOf(arr1, 16);

      // printing the array arr2
      System.out.println("Printing new array:");
      for (int i = 0; i < arr2.length; i++) {
         System.out.print(arr2[i]+" ");
      }
   }
}

Output

Printing 1st array:
15 10 45 
Printing new array:
15 10 45 0 0 0 0 0 0 0 0 0 0 0 0 0 



Comments