Thursday, August 5, 2021

How to copy Array in Java? Arrays copyOf and copyOfRange Example

There are multiple ways to copy elements from one array in Java, like you can manually copy elements by using a loop, create a clone of the array, use Arrays.copyOf() method or System.arrayCopy() to start copying elements from one array to another in Java. Even though both allow you to copy elements from source to destination array, the Arrays.copyOf() is much easier to use as it takes the just original array and the length of the new array. But, this means you cannot copy subarray using this method because you are not specifying to and from an index, but don't worry there is another method in the java.util.Arrays class to copy elements from one index to other in Java, the Arrays.copyOfRange() method. Both methods are overloaded to copy different types of arrays.

For example, the Arrays.copyOf() method is overloaded 9 times to allow you to copy all primitive array and reference arrays like you can use copyOf(originalArray, newLength) to copy booleans from a boolean array, integers from int array, characters from a char array, and bytes from the array and so on.

This method copies the specified array, truncating or padding the with the default values (if necessary), depending upon the type of array it's copying, so the copy has the specified length.

For example, if it is copying from a boolean array then it will pad with false if the value of the new length is greater than the length of the original array.

For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain the default value for the type of array, like false for a boolean array, zero or byte, int, char, and long array, 0.0 for float and double array, and null for reference type array.

Such indices will exist if and only if the specified length is greater than that of the original array. Btw, if you are not familiar with the array data structure itself, then I suggest you take these online courses on data structure and algorithms to find out more about essential data structure in depth.





How to copy a range of elements from one array to another in Java

The  Arrays.copyOfRange() is used to copy a range of values from one array to another in Java.  The copyOfRange(T[] original, int from, int to) takes three parameters, the original array, index of the first element or start index, and index of last element or end index.  It then copies the specified range of the specified array into a new array.

The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to).

Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, maybe greater than original.length, in which case default values are placed in all elements of the copy whose index is greater than or equal to the original.length - from e.g. false for a boolean array, zero for integral array and null for object array. 

The length of the returned array will be to - form, which means if you copy elements from 2 to 5 index then you will get the element at indices 2, 3, and 4, and the length of the array will be 3 (5 - 2) = 3.

Here is some sample code to copy an array in Java, both creating exact copy and a range of indices:


How to copy elements of one array to another array in Java - Arrays.copyOf and Arrays.copyOfRange Example



How to copy elements of one array to another

You can use the Arrays.copyOf() method to copy an array in Java. This method allows you to copy all or a subset of elements from the array in Java, but elements must be consecutive e.g. first 5 or first 10 elements of the array.

This is done by specifying the length argument for the new array in the Arrays.copyOf() method.

This method is also overloaded to copy 8 types of primitive array e.g. booleanintshort, char, byte, long, float, and double as well as reference type array.

String[] creditCards = {"Chase Sapphire Preferred Card ",
                                "Chase Freedom Unlimited",
                                "Amex Credit Card",
                                "Citi Simplicity Card ",
                                "Blue Cash Preferred Card from American 
                                                   Express ",
                                "NASCAR Credit Card from Credit One Bank"};
        
        
// let's copy this String array into another
String[] bestCreditCards = Arrays.copyOf(creditCards, creditCards.length);
        
System.out.println("original array: " + Arrays.toString(creditCards));
System.out.println("copy of array: " + Arrays.toString(bestCreditCards));

By the way, this is not the only way to make a copy of an array. You can also use the System.arrayCopy() method to copy an array in Java. I am not explaining that here because it's a little bit difficult to use and you should not be using unless you know what you are doing. Btw, these methods internally use the System.arrayCopy() itself.

The only place you need the System.arrayCopy() is if you are working on an older Java version where Arrays.copyOf() and Arrays.CopyOfRange() method is not available like  Java 1.5. These methods are only added in Java SE 6 but System.arrayCopy() is there from JDK 1 itself. See these free core Java online courses to learn more about essential methods of JDK.




Java Program to Copy Values from One Array to Other in Java

Here is my complete Java program to show you how you can make copies of an array in Java, both primitive and reference type array, as well how you can copy as many elements you want or how to copy a range of values or a sub-array in Java.

import java.util.Arrays;

/*
 * Java Program to copy elements from one array
 * to other in Java using Arrays.copyOf and
 * Arrays.copyOfRange methods
 */
public class Hello {

  public static void main(String args[]){
    
    // original array has 10 elements
    int[] original = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
    System.out.println("original array: " + Arrays.toString(original));
    
    // let's create an exact copy of the array
    int[] copy = Arrays.copyOf(original, 10);
    System.out.println("exact copy: " + Arrays.toString(copy));
    
    // let's copy only first 5 elements
    int[] firstFive = Arrays.copyOf(original, 5);
    System.out.println("exact copy: " + Arrays.toString(firstFive));
    
    // let's create a larger array by copying
    int[] bigger = Arrays.copyOf(original, 15);
    System.out.println("bigger copy: " + Arrays.toString(bigger));
    
    // Now, let's copy a range of values from one array to another
    // copying subarray from 2nd element to 5th element
    int[] range = Arrays.copyOfRange(original, 2, 5);
    System.out.println("copying range of values 2 to 5: " 
                          + Arrays.toString(range));
  }

}

Output:
original array: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
exact copy: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
exact copy: [10, 20, 30, 40, 50]
bigger copy: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 0, 0, 0, 0, 0]
copying range of values 2 to 5: [30, 40, 50]

If you look at the original array, we have 10 elements starting from 10 to 100, the first element, which is at index zero is 10. In the first example, we have created an exact copy of the array by passing the new length the same as the length of the old array and that's why Arrays.copyOf() method returned an array which was exact copy i.e. contains the same elements at the same indices.

In the next example, we have only copied the first five elements because the length of the new array was 5, half the length of the original array. Later we created a bigger array by supplying new lengths as 15, which means the first 10 elements are copied from the original array and the rest of the indices are padded with the default values for integer (because it was an integer array), which was zero.

In the last example, I have shown you how you can copy a range of indices or a sub-array by using the Arrays.copyOfRange() method. In order to copy values from the 3rd index to the 5th index, we passed 2 and 5, because the 3rd element resides at index 2. The start index is inclusive but the end index is not, hence the new array has 3 elements, from the 3rd, 4th and 5th index.


That's all about how to copy elements from one array to another in Java. You can use this trick to copy a string from one String array to another or integer from one string to another, but you cannot copy a string from a string array to an integer array because you cannot store different types of elements in an array.

All elements must be of the same type. Btw, this is not the only way to copy elements from one array to another, you can also use the Arrays.copyOfRange() method to copy a subarray in Java.


Other Data Structure and Algorithms  You may like
  • 50+ Data Structure and Algorithms Problems from Interviews (list)
  • 5 Books to Learn Data Structure and Algorithms in-depth (books
  • How to reverse an array in Java? (solution)
  • 20+ Array Codin problems from Interviews (questions)
  • How to remove duplicate elements from the array in Java? (solution)
  • Recursive InOrder traversal Algorithm (solution)
  • How to implement a recursive preorder algorithm in Java? (solution)
  • Recursive Post Order traversal Algorithm (solution)
  • How to implement a binary search tree in Java? (solution)
  • How to print leaf nodes of a binary tree without recursion? (solution)
  • 75+ Coding Interview Questions for Programmers (questions)
  • Iterative PreOrder traversal in a binary tree (solution)
  • How to count the number of leaf nodes in a given binary tree in Java? (solution)
  • 100+ Data Structure Coding Problems from Interviews (questions)
  • 21 String coding problems from interviews (questions)
  • Postorder binary tree traversal without recursion (solution)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)

Thanks for reading this article so far. If you like this Java Array tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.

P. S. - If you are looking for some Free Algorithm courses to improve your understanding of Data Structure and Algorithms, then you should also check these free Data structure and algorithms courses from Coursera and Udemy. It's completely free of cost and many people have already joined these courses. 

3 comments:

  1. is Arrays a key word in the method?I'm not getting it as a key word.

    ReplyDelete
    Replies
    1. Arrays is a class in java.util package. It contains utility methods related to array like copying elements from one array to other, searching like binary search, shuffling and others.

      Delete

  2. public static void main(String[] args) {

    float [][] g =new float [4][4] ;

    g[0][0] = 1.00f;
    g[0][1] = 1.00f;
    g[0][2] = 1.00f;
    g[0][3] = 1.00f;



    for (int i =0; i<4; i++ ) {

    for (int j =0 ; j<4 ; j++ ) {

    System.out.printf (" %.3f " ,g[i][j]) ;

    g[i+1][j] =( (j+1) * g[i][j]-1);

    //System.out.printf (" %.3f " ,g[i][j]) ;
    }
    System.out.println( " ");
    }
    }

    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.