To print each element of an ArrayList
on a new line in Java, you can use a loop to iterate over the elements of the ArrayList
and use the println
method of the PrintStream
class to print each element.
Here is an example of how you can print each element of an ArrayList
on a new line in Java:
import java.util.ArrayList; public class ArrayListPrinter { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); for (String element : list) { System.out.println(element); } } }
In this example, the main
method creates an ArrayList
of strings and adds three elements to it. Then, the main
method uses a loop to iterate over the elements of the ArrayList
and prints each element using the println
method of the PrintStream
class.
The println
method prints the argument followed by a new line, so each element of the ArrayList
will be printed on a new line. This code will print the following output:
apple banana cherry
Keep in mind that this is just one way to print each element of an ArrayList
on a new line in Java. You can use different techniques and data structures to achieve the same result, such as using the forEach
method of the Iterable
interface or the join
method of the String
class.