List to Array Conversion

Problem Statement: Write a Java program to Convert an ArrayList of strings into a string array.

Here’s a Java program that demonstrates how to convert an ArrayList of strings into a string array. I’ll provide an explanation of the program’s logic.

package com.javacodepoint.collection;

import java.util.ArrayList;

public class ArrayListToStringArrayDemo {

	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<>();
		arrayList.add("Hello");
		arrayList.add("World");
		arrayList.add("Java");
		arrayList.add("Programming");

		// Converting ArrayList to String array
		String[] stringArray = arrayList.toArray(new String[arrayList.size()]);

		// Printing the string array
		System.out.println("String Array:");
		for (String str : stringArray) {
			System.out.println(str);
		}
	}
}

OUTPUT:

String Array:
Hello
World
Java
Programming

Explanation:

  1. Creating the ArrayList: We create an ArrayList named arrayList and populate it with some strings.
  2. Converting to String Array: We use the toArray() method of the ArrayList class to convert the arrayList into a string array. The method requires an argument that specifies the target array type and size. In this case, we create a new String array with the same size as the ArrayList.
  3. Printing the String Array: We iterate through the stringArray and print each string using a for-each loop.

The toArray() method converts the ArrayList of strings into a string array, allowing you to work with the data in an array format.

See also: Create a stack using an ArrayList.

Java logical programs list


Java Basic Programs

Java String Programs

Java Programs based on the Collection Framework

Leave a Reply

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