Convert an ArrayList into a String in Java

Exercise:

Write a Java Program to convert the arraylist into a string .

Click Here to View the Solution!
import java.util.ArrayList;

public class ArrayToString {
    public static void main(String[] args) {
        ArrayList<String> languages= new ArrayList<>();
        languages.add("Java");
        languages.add("Python");
        languages.add("JavaScript");
        languages.add("CPP");
        languages.add("C");
        languages.add("Swift");
        System.out.println("ArrayList: " + languages);

        // convert the arraylist into a string
        String arraylist = languages.toString();
        System.out.println("String: " + arraylist);
    }
}
Click Here to View the Output!
ArrayList: [Java, Python, JavaScript, CPP, C, Swift]
 String: [Java, Python, JavaScript, CPP, C, Swift]
Click Here to View the Explanation!
  • In this example, a string type arraylist called languages is created firstly.
  • Elements are added to this arraylist and then the list is printed on the screen.
  • Next, languages is converted into a single string arraylist using the toString() method and so, the string arraylist is printed on the screen.

%d bloggers like this: