Java Collection Tutorial - Java Arrays.copyOf(byte[] original, int newLength)








Syntax

Arrays.copyOf(byte[] original, int newLength) has the following syntax.

public static byte[] copyOf(byte[] original,  int newLength)

Example

In the following code shows how to use Arrays.copyOf(byte[] original, int newLength) method.

/*w w w.j a  va 2s.  c o  m*/

import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    
    byte[] arr1 = new byte[] {5, 15, 25};

    System.out.println(Arrays.toString(arr1));

    // copying array arr1 to arr2 with newlength as 5
    byte[] arr2 = Arrays.copyOf(arr1, 5);
    arr2[3] = 0;
    arr2[4] = 1;

    System.out.println(Arrays.toString(arr2));
  }
}

The code above generates the following result.