The syntax of the toString() method is:
arraylist.toString()
Here, arraylist is an object of the ArrayList class.
toString() Parameters
The toString() method doesn't take any parameters.
toString() Return Values
- returns a string representation of the arraylist
Example: Convert ArrayList to String
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> languages= new ArrayList<>();
// Add elements in the ArrayList
languages.add("Java");
languages.add("Python");
languages.add("C");
System.out.println("ArrayList: " + languages);
// convert ArrayList to String
String list = languages.toString();
System.out.println("String: " + list);
}
}
Output
ArrayList: [Java, Python, C] String: [Java, Python, C]
In the above example, we have created an arraylist named languages. Notice the line,
String list = languages.toString();
Here, we have used the toString() method to convert the arraylist into a string. The method converts the entire arraylist into a single String.
Note: The ArrayList class does not have its own toString() method. Rather it overrides the method from the Object class.
Also Read: