How to Copy Range of Elements From an Array in Java


Here this example we will demonstrate how to copy range of elements from an array to another array.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class CopyRangeArray {

	public static void main(String[] args) {
		//Create Int array.
		int[] intArray = {1,2,3,4,5,6};
		System.out.println("intArray contains : ");
		for(int i=0; i<intArray.length; i++) {
			 System.out.print(intArray[i]+"  ");
		}
		
		/*
		 * Use the method Arrays.copyOfRange() 
		 * to copy range of object from existing array to new array.
		 */
		int[] newIntArray = Arrays.copyOfRange(intArray, 1, 3);
		System.out.println("nnewIntArray contains : ");
		for(int i=0; i<newIntArray.length; i++) {
			 System.out.print(newIntArray[i]+"  ");
		}
	}

}

Output:

intArray contains : 
1  2  3  4  5  6  
newIntArray contains : 
2  3  

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments