Array Copy in Java

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Copying array elements in Java is a seemingly simple task, but naive methods can lead to unexpected results. In this brief tutorial, we explore various array copying methods, emphasizing the importance of careful implementation to avoid undesired program behaviors.

Example

In this example, we are going to check how to copy an array in java using for loop.

Output

Code Explanation

In the above example, we have created an array with elements 1,2,3. Then created another element and assign elements to another array. This will create a copy of array. To check if a copy is created we checked it using the equals() method this method returns false means both arrays have different references.

Problem with Simple Assignment Operation

We are essentially assigning a reference to the array when we write array2 = array1. Because both array1 and array2 refer to the same location, any changes we make to one array will also affect the other arrays. We can also verify it with the code as shown below as follows:

Output

Code Explanation

In theabovee code, we have created an array with elements 1,2,3. Created another array and assign the previous array to the new array. As the assignment operator will assign a reference to the previous array so equals() method will return true.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Java Copy Array Various Methods

There are many methods of copying an array we are going to discuss each one of them in detail.

Manual Copying Using For Loop

Copying one element at a time while iterating through every element of the original array provided. Using this method ensures that any changes to b won't affect the initial array a, as seen in the example below follows this example we, are going to check how to copy an array in java using for loop

Output

Code Explanation

In above example, we have created an array with elements 1,2,3. Then created another element and assign elements to another array. This will create a copy of array. To check if ia f copy is created we checked it usinthe g equals() method this method returns false m ns both arrays have a differenreferencesce.

Using clone() Method

The act of making an exact duplicate of an object is referred to as object cloning. It makes a new instance of the current object's class and fills all of its fields exactly with the data found in the corresponding fields of the current object.

In this example we are going to check how to cop an array in java usinthe g clone method.

Output

Code Explanation

In this example, we have created an array with element 1,2,3,4,5,6 . We have used the clone() method to create a copy of array array1.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Using arraycopy() Method

We can also use the System.arraycopy()Method. The system is present in `java.lang package.

This method starts the copy action from the source position to the target position till the specified length.

The target array's length is equal to the number of elements copied there. It offers a simple method for copying a section of an array to another.

A NullPointerException is thrown if any of the array arguments are null. An IndexOutOfBoundException is thrown if any of the integer inputs are negative or outside of the acceptable range. Syntax of arraycopy() method is as follows

Parameters:

  • src array.
  • srcPos index from which copying starts.
  • dest stands for the destination array.
  • destPos is the index from which the copied elements are added to the destination arra.
  • length is the size of the copied subarray.

In this example, we are going to check how to copy an array in java usingarraycopy() method.

Output

Code Explanation

In the above code f,first, we have created an an array withelementst 1,2,3,4,5,6,7. We have used arraycopy() method with the following parameters src:a,dest:b, srcpos:0, destpos :0, and length as 3.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

Using copyOf() Method of Arrays class

The function java.util.Arrays.copyOf(int[] original, int newLength) duplicates the provided array, trimming or padding with zeros (if needed) to make the copy the desired length. The two arrays will have the same values for all indices that are valid in both the original array and the duplicate. The copy will contain 0 for any indices that are accurate in the copy but not the original. Only if the given length is larger than the length of the original array will such indices be present.

Syntax

Parameters

original − array to be copied. newLength − length of the copy to be returned.

Return

This method gives back a copy of the original array that has been padded with zeros or trimmed to the desired length.

In this example, we are going to discuss how to copy an array in java using the copyof() method

Code Output

Code Explanation

In the above example we have created an array with elements 1,2,3,4,5,6and created a copyanof an array using the Arrays.copyOf() method with original arrays parameters as a and length of the array as newlength parameter.

Using copyOfRange() Method of Arrays Class

This function creates a new array by copying the desired range of the supplied array.

In this section, we are going to check how to copy an array in java using copyofRange().

Syntax

Parameters:

  • original: array from which to copy a range in the original
  • from: the range's starting index to be copied
  • to: exclusive final index of the range to be copied

Output

Code Explanation

In the above example, we have created an array with elements 1 8 3 5 9 10and created a copy of an array using the Arrays.copyOfRange() method fthe from 2 indexthe to 6 index.

Copying 2d Arrays Using Loop

We may use the for loop to copy the 2-dimensional array like how we clone a single-dimensional array.

In this example, we are going to check how to copy an array in java of type 2D.

Output

Code Explanation

In the above example we have created a copy of a 2D array using for loop similar top 1D array.

Conclusion

  • Because the assignment procedure would result in both variables pointing to the same array, arrays in Java cannot be copied using the = operator.
  • There arevariouss methods to copy an Object.
  • Manual Copying using for loop: copying one element at a time while iterating through every element of the original array provided
  • using clone() method
  • using arraycopy() method
  • using copyOf() method
  • using copyOfRange() method
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more