GuideFoot - Learn Together, Grow Smarter. Logo

In Computers and Technology / High School | 2025-07-08

Refer to the code given below: ```java public class Q4 { public static void main(String[] args) { List departments = Arrays.asList("Civil", "Mechanical", "Computers", "Electronics"); } } ``` Identify the correct option to convert the given List departments to String[] using Java 11 Features: 1. String[] departmentsArray = (String[]) departments.toArray(); 2. String[] departmentsArray = departments.toArray(); 3. String[] departmentsArray = departments.toArray(String[]::new); 4. String[] departmentsArray = departments.toArray(String[]);

Asked by jgibson6280

Answer (1)

The given Java code snippet involves converting a List of departments into a String[] array. To achieve this using Java 11 features, you should use the List.toArray(IntFunction<T[]>) method. This method was introduced in Java 11 and allows you to specify a generator function to create the appropriate type of array.
Here's how the options provided can be evaluated:

String[] departmentsArray = (String[]) departments.toArray();

This option attempts to cast the result of toArray() to String[]. This is incorrect because toArray() returns an Object[] by default, leading to a ClassCastException at runtime.


String[] departmentsArray = departments.toArray();

This option tries to directly assign the result of toArray() to a String[]. However, toArray() returns an Object[], not a String[], leading to a compile-time error.


String[] departmentsArray = departments.toArray(String[]::new);

This option is correct. It uses the method reference String[]::new which acts as a generator for creating a new String array of the appropriate size. This utilizes the List.toArray(IntFunction<T[]>) method, which ensures that the returned array is indeed a String[].


String[] departmentsArray = departments.toArray(String[]);

This option is incorrect because the syntax for converting a list to an array using toArray() requires a generator or an existing array, which is not provided here in the correct form.



Therefore, the correct option is:

String[] departmentsArray = departments.toArray(String[]::new);

This approach provides a clean and efficient way to convert a list to an array, leveraging the enhancements made in Java 11.

Answered by MasonWilliamTurner | 2025-07-21