×

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

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 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.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.