1. Introduction
In Java, converting an ArrayList to a String representation is a common task. This conversion is often required when we need to print, log, or store the ArrayList elements as a String. In this post, we will explore how to convert an ArrayList to a String in Java using the toString() method and the String.join() method.
2. Program Steps
1. Create an ArrayList and add some elements to it.
2. Convert the ArrayList to a String using the toString() method and print the result.
3. Convert the ArrayList to a String using the String.join() method and print the result.
3. Code Program
import java.util.ArrayList;
public class ArrayListToString {
public static void main(String[] args) {
// Step 1: Create an ArrayList and add some elements to it
ArrayList<String> fruitList = new ArrayList<>();
fruitList.add("Apple");
fruitList.add("Banana");
fruitList.add("Cherry");
// Step 2: Convert the ArrayList to a String using the toString() method
String resultUsingToString = fruitList.toString();
System.out.println("String using toString(): " + resultUsingToString);
// Step 3: Convert the ArrayList to a String using the String.join() method
String resultUsingJoin = String.join(", ", fruitList);
System.out.println("String using join(): " + resultUsingJoin);
}
}
Output:
String using toString(): [Apple, Banana, Cherry] String using join(): Apple, Banana, Cherry
4. Step By Step Explanation
Step 1: We create an ArrayList named fruitList and add three elements ("Apple", "Banana", and "Cherry") to it.
Step 2: The toString() method of the ArrayList class is used to convert fruitList to a String. The toString() method returns a string representation of the ArrayList, including square brackets. The resulting String is printed to the console.
Step 3: The String.join() method is another way to convert an ArrayList to a String. It concatenates the ArrayList elements with a specified delimiter (in this case, a comma followed by a space). The String resulting from String.join() does not include square brackets and is printed to the console.