Printing the ArrayList of user input

Now, we can simply use println to print our ArrayList out to the user. Note that the println code line doesn't know how to take an ArrayList as input. Actually, it might, but we should explicitly use the toString() function, which almost every object in Java implements:

package echo; 
 
import java.util.*; 
 
public class Echo { 
    public static void main(String[] args) { 
        Scanner reader = new Scanner(System.in); 
        ArrayList<String> memory = new ArrayList<String>(); 
         
        while(true) 
        { 
            memory.add(reader.nextLine()); 
            System.out.println(memory.toString()); 
        } 
    } 
} 

Now, when we run our program, we'll be prompted for some user input, and we'll see the input echoed back out at us. If we give Java some more input, we'll see our ...

Get Java Programming for Beginners now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.