System.arraycopy() Method in Java with Examples
Last Updated :
24 May, 2022
System class in Java is a part of the lang package and comes with many different fields and methods, and System.arraycopy() is among the 28 methods. It copies the source array from a specific index value and pastes it into another array of either the same length or different lengths, it doesn’t matter and copies it till a certain length which is also up to us to decide. Given an array of a fixed length. The task is to add a new element at a specific index of the array.
--> java.lang Package
--> System Class
--> arraycopy() Method
Syntax:
public static void arraycopy(Object Source, int sourceStartIndex,
Object Destination, int DestinationStartIndex, int size)
Parameters:
- Source: This is the array from which elements are to be copied.
- sourceStartIndex: This is the source start position.
- Destination: This is the array to which elements are supposed to be copied.
- DestinationStartIndex: This is the destination start position.
- size: The number of elements to be copied.
Illustration
Input: arr[] = { 1, 2, 3, 4, 5 }, index = 2, element = 6
Output: arr[] = { 1, 2, 6, 3, 4, 5 }
Input: arr[] = { 4, 5, 9, 8, 1 }, index = 3, element = 3
Output: arr[] = { 4, 5, 3)
Approach:
- Get the array and the index – p
- Create a new array of size one more than the size of the original array.
- Copy the elements from starting till index from the original array to the other array using System.arraycopy().
- At p, add the new element in the new Array which has the size of 1 more than the actual array
- Copy the elements from p of the original array and paste them from index p+1 in the new array till the end using System.arraycopy().
- Print the new array
Below is the implementation of the above approach.
Java
import java.lang.System;
import java.util.Arrays;
import java.util.Scanner;
public class GFG {
public static void main(String[] args)
{
int [] A = { 1 , 2 , 3 , 4 , 5 , 6 };
System.out.print( "Original Array : " );
System.out.print(Arrays.toString(A));
int n = A.length;
int p = 2 ;
int x = 10 ;
int [] B = new int [n + 1 ];
System.arraycopy(A, 0 , B, 0 , p);
System.arraycopy(A, p, B, p + 1 , n - p);
B[p] = x;
System.out.println();
System.out.print( "New Array : "
+ Arrays.toString(B));
}
}
|
Output
Original Array : [1, 2, 3, 4, 5, 6]
New Array : [1, 2, 10, 3, 4, 5, 6]
Share your thoughts in the comments
Please Login to comment...