Arrays copyOf() in Java with examples
Last Updated :
28 Mar, 2023
java.util.Arrays.copyOf() method is in java.util.Arrays class. It copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.
Syntax:
copyOf(int[] original, int newLength)
- original – original array
- newLength – copy of an original array
Java
import java.util.Arrays;
public class Main
{
public static void main(String args[])
{
int [] org = new int [] { 1 , 2 , 3 };
System.out.println( "Original Array" );
for ( int i = 0 ; i < org.length; i++)
System.out.print(org[i] + " " );
int [] copy = Arrays.copyOf(org, 5 );
copy[ 3 ] = 11 ;
copy[ 4 ] = 55 ;
System.out.println( "\nNew array copy after modifications:" );
for ( int i = 0 ; i < copy.length; i++)
System.out.print(copy[i] + " " );
}
}
|
Output
Original Array
1 2 3
New array copy after modifications:
1 2 3 11 55
What happens if the length of a copied array is greater than the original array? The two arrays will have same values for all the indices that are valid in original array and new array. However, the indices missing in original will have zero in copy in case the copied array length is more than the original array.
Java
import java.util.Arrays;
public class Main
{
public static void main(String args[])
{
int [] org = new int [] { 1 , 2 , 3 };
System.out.println( "Original Array :" );
for ( int i = 0 ; i < org.length; i++)
System.out.print(org[i] + " " );
int [] copy = Arrays.copyOf(org, 5 );
System.out.print( "\nNew array copy (of higher length):\n" );
for ( int i = 0 ; i < copy.length; i++)
System.out.print(copy[i] + " " );
}
}
|
Output
Original Array :
1 2 3
New array copy (of higher length):
1 2 3 0 0
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...