135k views
2 votes
Consider the following code snippet: String[] data = { "abc", "def", "ghi", "jkl" }; String [] data2; In Java 6 and later, which statement copies the data array to the data2 array?

1 Answer

7 votes

Answer:

String[] data2 = Arrays.copyOf(data, 4); is the statement which copies the data array to the data2 array in java 6 .

Step-by-step explanation:

The Arrays.copyOf() function copies the data from first array to another array in java .We pass the two argument in this function first argument is the name of first array and second the length of first array .

Following are the program in java

import java.util.Arrays; // import package

public class Main

{

public static void main(String[] args) // main function

{

String[] data = { "abc", "def", "ghi", "jkl" }; // string declaration

// printing the array data1

System.out.println("before copy new array:");

for (int k = 0; k < data.length; k++)

{

System.out.println(data[k]);

}

String[] data2 = Arrays.copyOf(data, 4);

// printing the array data2

System.out.println("after copy new array:");

for (int k = 0; k < data2.length; k++)

{

System.out.println(data2[k]);

}}}

Output:

before copy new array:

abc

def

ghi

jkl

after copy new array:

abc

def

ghi

jkl

User Oxnz
by
7.3k points