w3resource

Java: Convert an array to ArrayList

Java Array: Exercise-20 with Solution

Write a Java program to convert an array to an ArrayList.

Pictorial Presentation:

Java Array Exercises:  Convert an array to ArrayList

Sample Solution:

Java Code :

// Import the ArrayList and Arrays classes from the Java utility library.
import java.util.ArrayList;
import java.util.Arrays;

// Define a class named Exercise20.
public class Exercise20 {
    public static void main(String[] args) {
        // Create an array of strings.
        String[] my_array = new String[] {"Python", "JAVA", "PHP", "Perl", "C#", "C++"};

        // Create an ArrayList of strings and initialize it with the contents of the array.
        ArrayList list = new ArrayList(Arrays.asList(my_array));

        // Print the ArrayList to the console.
        System.out.println(list);
    }
}

Sample Output:

[Python, JAVA, PHP, Perl, C#, C++] 

Flowchart:

Flowchart: Java exercises: Convert an array to ArrayList

Java Code Editor:

Previous: Write a Java program to add two matrices of the same size.
Next: Write a Java program to convert an ArrayList to an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/array/java-array-exercise-20.php