VOOZH about

URL: https://www.geeksforgeeks.org/java/system-arraycopy-method-in-java-with-examples/

⇱ System.arraycopy() Method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:

  1. Get the array and the index - p
  2. Create a new array of size one more than the size of the original array.
  3. Copy the elements from starting till index from the original array to the other array using System.arraycopy().
  4. At p, add the new element in the new Array which has the size of 1 more than the actual array
  5. 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().
  6. Print the new array

Below is the implementation of the above approach.


Output
Original Array : [1, 2, 3, 4, 5, 6]
New Array : [1, 2, 10, 3, 4, 5, 6]
Comment
Article Tags: