Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Arrays.equals() in Java with Examples
Next article icon

Arrays copyOf() in Java with Examples

Last Updated : 11 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Arrays.copyOf() is a method of java.util.Arrays class. It is used to copy the specified array, truncating or padding with false (for boolean arrays) if necessary so that the copy has the specified length.

This method can be used with both 1D and 2D arrays, but it’s important to note that Arrays.copyOf() performs a shallow copy, meaning that if you’re copying an array of objects, the objects themselves are not duplicated—only the references to them.

Example:

The below example shows the basic use of Arrays.copyOf() method to create a copy of an array with a specified length.

Java
import java.util.Arrays;  public class ArraysCopyOf {        public static void main(String[] args)    {         int[] arr1 = {1, 2, 3, 4, 5};          // copy the array to a new array with the same length         int[] arr2 = Arrays.copyOf(arr1, arr1.length);          System.out.println("Original Array: " + Arrays.toString(arr1));         System.out.println("Copied Array: " + Arrays.toString(arr2));     } } 

Output
Original Array: [1, 2, 3, 4, 5] Copied Array: [1, 2, 3, 4, 5] 

This demonstrates how Arrays.copyOf() method can be used to duplicate a 1D array with basic functionality before exploring complex examples.

Table of Content

  • Copying 1D Arrays
    • Syntax to Copy 1D Array
    • Example of Copying 1D Array
    • Copying 1D Array with a Larger Length
  • Copying 2D Arrays
    • Syntax to Copy 2D Array
    • Example of Copying 2D Array

Copying 1D Arrays

Here, we will learn how to use Arrays.copyOf() method to copy a 1D array and then modify its extra elements.

Syntax to Copy 1D Array

Arrays.copyOf(int [] original, int newLength);

  • original: The original array to be copied.
  • newLength: The desired length of the new copy.

Example of Copying 1D Array

Java
// Java program to illustrate copyOf()  // method for 1D arrays import java.util.Arrays;  public class Main {     public static void main(String[] args) {                  // initialize original array         int[] arr1 = new int[] {1, 2, 3};          System.out.println("Original Array:");         for (int i = 0; i < arr1.length; i++)             System.out.print(arr1[i] + " ");          // Copying array 'arr1' to 'arr2'         // with specified size         int[] arr2 = Arrays.copyOf(arr1, 5);          // Modifying the newly added elements         arr2[3] = 4;         arr2[4] = 5;          // Displaying the copied          // array after modifications         System.out.println("\n\nCopied array after modifications:");         for (int i = 0; i < arr2.length; i++)             System.out.print(arr2[i] + " ");     } } 

Output
Original Array: 1 2 3   Copied array after modifications: 1 2 3 4 5 

Copying 1D Array with a Larger Length

When the length of the copied array is greater than the original, the new array is padded with default values (0 for int, false for boolean, and null for reference types) to fill the remaining indices.

Example:

Java
// Java program to illustrate the use of copyOf // when new array is of higher length import java.util.Arrays;  public class Main {     public static void main(String args[]) {          // initializing an array original     int[] arr1 = new int[] {1, 2 ,3};          System.out.println("Original Array:");     for (int i = 0; i < arr1.length; i++)         System.out.print(arr1[i] + " ");              // copying array arr1 to arr2     // Here, new array has 5 elements      int[] arr2 = Arrays.copyOf(arr1, 5);          System.out.print("\nNew array of higher length:\n");     for (int i = 0; i < arr2.length; i++)         System.out.print(arr2[i] + " ");     } } 

Output
Original Array: 1 2 3  New array of higher length: 1 2 3 0 0 

Copying 2D Arrays

When working with 2D arrays, the Arrays.copyOf() method performs a shallow copy, meaning only the references to each row are copied. For a deep copy of the rows in a 2D array, you would need to copy each row individually.

Syntax to Copy 2D Array

Arrays.copyOf(originalArray, newLength);

Example of Copying 2D Array

Java
import java.util.Arrays;  public class Main {        public static void main(String[] args) {                  // Original 2D array         int[][] arr1 = {             {1, 2, 3},             {4, 5, 6},             {7, 8, 9}         };          // Copying the 2D array         int[][] arr2 = copy2DArray(arr1);          System.out.println("Original Array:");         print2DArray(arr1);          System.out.println("Copied Array:");         print2DArray(arr2);     }      // Method to copy a 2D array     public static int[][] copy2DArray(int[][] arr1) {                  // Create a new 2D array with the same          // number of rows as the original         int[][] arr2 = new int[arr1.length][];                  // Copy each row using Arrays.copyOf() method         for (int i = 0; i < arr1.length; i++) {             arr2[i] = Arrays.copyOf(arr1[i], arr1[i].length);         }                  return arr2;     }      // Method to print a 2D array     public static void print2DArray(int[][] arr3) {         for (int[] r : arr3) {             System.out.println(Arrays.toString(r));         }     } } 

Output
Original Array: [1, 2, 3] [4, 5, 6] [7, 8, 9] Copied Array: [1, 2, 3] [4, 5, 6] [7, 8, 9] 



Next Article
Arrays.equals() in Java with Examples
author
kartik
Improve
Article Tags :
  • Java
  • Java - util package
  • Java-Arrays
  • Java-Functions
Practice Tags :
  • Java

Similar Reads

  • Arrays.copyOfRange() in Java with Examples
    Arrays copyOfRange() method is used to create a new array by copying a specified range of elements from an existing array. It provides a way to copy a subset of elements between two indices by creating a new array of the same type. Below is a simple example that uses Arrays.copyOfRange() method to c
    4 min read
  • Arrays.equals() in Java with Examples
    The Arrays.equals() method comes under the Arrays class in Java. It is used to check two arrays, whether single-dimensional or multi-dimensional array are equal or not. Example: Below is a simple example that uses Arrays.equals() method to check if two arrays of integers are equal or not. [GFGTABS]
    3 min read
  • Arrays.fill() in Java with Examples
    The Arrays.fill() is a method in the java.util.Arrays class. This method assigns a specified value to each element of an entire array or a specified range within the specified array. Example: Now let's understand this with the below simple example to fill an entire array with a specified value: [GFG
    3 min read
  • Arrays.deepToString() in Java with Example
    The Arrays.deepToString() method comes under the Arrays class in Java. It is used to return a string representation of the "deep contents" of a specified array. It handles multidimensional arrays by including the contents of nested arrays. Example: Below is a simple example that uses Arrays.deepToSt
    3 min read
  • Arrays.toString() in Java with Examples
    The Arrays.toString() method belongs to the Arrays class in Java. It converts an array into its string representation consisting of a list of the array's elements. In the case of an Object Array, if the array contains other arrays as elements, their string representation shows memory addresses inste
    3 min read
  • Java Arrays compare() Method with Examples
    The Arrays compare() method in Java is a part of the java.util package to compare arrays lexicographically (dictionary order). This method is useful for ordering arrays and different overloads for different types including boolean, byte, char, double, float, int, long, short, and Object arrays. Exam
    3 min read
  • Arrays asList() Method in Java with Examples
    The Arrays.asList() method in Java is part of the java.util.Arrays class, which is used to convert an array into a fixed-size list. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray(). Example: Below is a simple example of the Arrays a
    4 min read
  • Buffer array() methods in Java with Examples
    The array() method of java.nio.Buffer class is used to return the array that backs the taken buffer. This method is intended to allow array-backed buffers to be passed to native code more efficiently. Concrete subclasses provide more strongly-typed return values for this method. Modifications to thi
    3 min read
  • Arrays.binarySearch() in Java with Examples | Set 1
    In Java, the Arrays.binarySearch() method searches the specified array of the given data type for the specified value using the binary search algorithm. The array must be sorted by the Arrays.sort() method before making this call. If it is not sorted, the results are undefined. Example: Below is a s
    3 min read
  • ArrayList size() Method in Java with Examples
    In Java, the size() method is used to get the number of elements in an ArrayList. Example 1: Here, we will use the size() method to get the number of elements in an ArrayList of integers. [GFGTABS] Java // Java program to demonstrate the use of // size() method for Integer ArrayList import java.util
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences