×

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To test their uniqueness, we must clone the array. For instance, to determine whether or not a string is a palindrome, we first transform the string into a character array and create a temporary copy of the char array. The char array's elements are now reversed and compared to the temporary file containing the original string.

Using Array Elements to Copy

It is a simple-minded method of array cloning. This approach involves iterating the initial array and putting each piece into a different array.

CloneArray1.java

// import packages   
import java. Util. Scanner ;  
public class CloneArray1 {  
    // Main method where execution of the program starts
    public static void main ( String [ ] args )  
    {  
         int original [ ] ;  
         int clone [ ] ;  
         int s ;  
         Scanner sc = new Scanner ( System . in) ;  
         System . out. println ( " Enter Size of the array " ) ;  
         s = sc . nextInt ( ) ;  
         original = new int [ s ] ;  
         clone = new int [ s ] ;  
         System . out . println ( " Elements of the original array is " ) ;  
         for ( int i = 0 ; i < s ; i++ )
         {  
             original [i] = sc . nextInt ( ) ;  
         }  
         sc . close ( ) ;  
         for ( int i = 0 ; i < original . length ; i++ )
         {  
             clone [ i ] = original [ i] ;  
         }    
         System . out . println ( " Elements of the original array: " ) ;  
         for (int i = 0 ; i < original . length ; i++ )
         {  
             System . out . print ( original [ i ] + "  " ) ;  
         }  
         System . out . println ( " \n \n Elements of the clone array : " ) ;  
         for (int i = 0; i < clone . length ; i++ ) 
         {  
             System . out . print ( clone [ i ] + " " ) ;  
         }  
    }  
}

Output

Java Clone Array

Java clone() method

The original array was iterated in the function above to create a copy of it. The clone() function of the Object class is another option that may be used to duplicate the provided array quickly.

Clone2.java

//import packages 
import java . util . Scanner ;  
public class Clone2 {  
    public static void main ( String [ ] args )  
    {  
         int original [ ] ;  
         int clone [ ] ;  
         int s ;  
         Scanner sc = new Scanner ( System . in ) ;  
         System . out . println ( " size of the array is " ) ;  
         s = sc . nextInt ( ) ;  
         original = new int [ s ] ;  
         clone = new int [ s ] ;  
         System . out . println ( " Enter elements of the original array : " ) ;  
         for ( int k = 0 ; k < s ; k++ ) {  
             original [ k ] = sc . nextInt ( ) ;  
         }  
         sc . close ( ) ;  
         clone = original . clone ( ) ;  
         System . out . println ( " Elements of the original array : " ) ;  
         for ( int j = 0 ; j < original . length ; j++ ) {  
             System . out . print ( original [ j ] + " " ) ;  
         }    
         System . out . println ( " \n\n Elements of the clone array: " ) ;  
         for ( int k = 0 ; k < clone . length ; k++ ) {  
             System . out . print ( clone [ k ] + " " ) ;  
         }  
    }  
}

Output

Java Clone Array

Java arraycopy() method 

The arraycopy() function may be found in the System class in the java.lang.* package. This technique copies a specific area of one array into another array. Copies an array, starting at the specified position in the source array, to the specified position in the destination array. A subsequence of array components are transferred from the source array identified by src to the destination array indicated by dest.

Program for clone array using arraycopy() method

ArrayCopy.java

//import  packages 
import java . util . *;  
public class ArrayCopy {  
    // Main section where execution of the program starts 
    public static void main(String[] args)  
    {  
        // declaring array variables
         int original[];  
         int clone[];  
         // size of the array
         int s;  
         // creating object for scanner class
         Scanner sc = new Scanner(System.in);  
         System . out . println ( " size of the array is " ) ;  
         s = sc . nextInt ( ) ;  
         original = new int[s];  
         clone = new int[s];  
         System . out . println ( " the  array elements are " ) ;  
         for ( int k = 0 ; k < s ; k++ )
         {  
             original [ k ] = sc . nextInt ( ) ;  
         }  
         // closing the scanner class
         sc . close ( ) ;  
         System . arraycopy ( original , 0 , clone , 0 , s ) ;  
         System . out . println ( " the original array elements are " ) ;  
         for (int j = 0 ; j < original . length ; j++ )
         {  
             System . out . print ( original [ j ] + " " ) ;  
         }  
         System . out . println ( "\n Elements of  clone array :" ) ;  
         for ( int k = 0 ; k < clone . length ; k++ ) 
         {  
             System . out . print ( clone [ k ] + " " ) ;  
         }  
    }  
}  

Output

Java Clone Array

Java CopyOf() Method

The copyOf() function of the Arrays class, found in the java.util package, is comparable to the clone() and arraycopy() methods.Here, len designates the length of the array that will be copied, while arr designates the original array.

Program for clone array using copyOf() method

CopyOf.java

//import packages
import java.util.*;  
public class CopyOf {  
    public static void main(String[] args)  
    {  
         int original[];  
         int clone[];  
         int s;  
         Scanner sc = new Scanner(System.in);  
         System . out . println ( " size of array  the array is" ) ;  
         s = sc . nextInt ( ) ;  
         original = new int [ s ] ;  
         clone = new int [ s ] ;  
         System . out . println ( " the original array elements are " ) ;  
         for ( int k = 0 ; k < s ; k++ ) 
         {  
             original [ k ] = sc . nextInt ( ) ;  
         }  
         sc.close();  
         clone = Arrays . copyOf ( original , s ) ;  
         System . out . println ( " The original array  elements are : " ) ;  
         for ( int j = 0 ; j < original . length ; j++ )
         {  
             System . out . print ( original [ j ] + " " ) ;  
         }  
         System . out . println ( " The cloned array elements are " ) ;  
      
         for  ( int j = 0 ; j  <  clone . length ; j++ ) {  
             System . out . print (clone [ j ] + " " ) ;  
         }  
    }  
}  

Output

Java Clone Array

Java copyOfRange() Method

Arrays class has copyOfRange() function to clone an array, which is similar to copyOf() method. The original array's elements from the specified range are copied into the new array using the copyOfRange() function. Here, the element's starting and end indexes are defined.

Program for clone array using copyOfRange() method

CopyOfRange.java

//import packages  
import java.util.Scanner;  
import java.util.Arrays;  
public class CopyOfRange {  
    public static void main(String[] args)  
    {  
         int original [ ] ;  
         int clone [ ] ;  
         int s ;  
         Scanner sc = new Scanner(System.in);  
         System . out . println ( " Enter  array size ." ) ;  
         s = sc.nextInt ( ) ;  
         original = new int [ s ] ;  
         clone = new int [ s ] ;  
         System . out . println ( " The original array elements are " ) ;  
         for ( int j = 0 ; j < s ; j++ ) {  
             original [ j ] = sc . nextInt ( ) ;  
         }  
         clone = Arrays.copyOfRange ( original , 0 , s ) ;  
         System . out . println ( " Elements of  original array: " ) ;  
         for ( int j = 0 ; j < original . length ; j++ )
         {  
             System . out . print (original [ j ] + " " ) ;  
         }  
         System . out . println ( " \n New  cloned array elements are : " ) ;  
         for ( int k = 0 ; k < clone . length ; k++ )
         {  
             System . out . print ( clone [ k ] + " " ) ;  
         }  
    }  
}

Output

Java Clone Array

Related Topics

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

How to create a mirror image of a 2D array in Java

Problem Statement We have provided a list of m x n. here m indicates rows, and n indicates columns). Printing the fresh matrices should result in a mirror reflection of an...

2 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.