Share & learn

Through Innovative Digital Library

What is Arrays.copyOf() and Arrays.copyOfRange() method in Java?

Explain about Arrays.copyOf() and Arrays.copyOfRange().
 



Answers

Posted by Paul on April 30th 2018 08:38 AM

Arrays.copyOf() and Arrays.copyOfRange() these both methods are provided by java in order to copy elements of an array. Arrays.copyOf() : - This method is in java.util.Arrays class. - This method copies the particular array, truncating or padding with false, so the copy has the specified length. Syntax : copyOf(int[] original, int newLength) Here for an example a code is written, in which an array is created, which will be copied using copyOf() method. Here is the code :

//Java program to demonstrate copyOf() method
import java.util.Arrays;

public class 
CopyOfDemo {

    public static 
void main(String args[]) {

        
// create an array
        
int[] arr = new int[] { 12};

        
System.out.println("Original Array");
        
        for (
int i 0arr.lengthi++)
            
System.out.print(arr[i] + " ");

        
// copy array arr to copy_arr
        
int[] copy_arr Arrays.copyOf(arr5);

        
// change some elements of copy_arr
        
copy_arr[3] = 9;
        
copy_arr[4] = 6;

        
System.out.println("\n\nNew array copy after modifications:");
        for (
int i 0copy_arr.lengthi++)
            
System.out.print(copy_arr[i] + " ");
        
    }
}

Posted by Paul on April 30th 2018 08:38 AM

Arrays.copyOfRange() in Java : Using this method you can create copy of array elements within given range. Syntax : public static int[] copyOfRange(int[] original_array, int from_index, int to_index) Here is the code :

//Java program to demonstrate copyOfRange() method
import java.util.Arrays;

public class 
CopyOfRangeDemo {
    public static 
void main(String args[]) {
        
int arr[] = { 1345678};

        
// to index is within the range
        
int[] copy_arr Arrays.copyOfRange(arr26);
        for (
int i copy_arr)
            
System.out.print("  ");

        
System.out.println();
        
// to index is out of range
        // It assigns Zero to all the index out of range
        
int[] copy1 Arrays.copyOfRange(arr4arr.length 3);

        for (
int i copy1)
            
System.out.print("  ");

    }
}

Posted by Paul on April 30th 2018 08:38 AM

So the basic difference between copyOf() and copyOfRange() is that copyOf() starts copying elements of an array form the 0th (i.e. first element ) index of the original array and copies the particular number of elements on the other hand copyOfRange() can copy the range of elements form the original array.

Answer Question

Your email address will not be published. Required fields are marked *

  • Minimum 20 character
IRSK

related questions

Most liked questions

Most answered questions

Login
IRSK Refresh
Register
IRSK Refresh
Forgot password
Ask a Question
Minimum 20 character
Minimum 20 character
Reply
Minimum 20 character
IRSK Refresh