Write each character of a string to a queue (FIFO) and then read it back one character at a time.

Question:
Write each character of a string to a queue (FIFO) and then read it back one character at a time.

Answer:
Here is an example using the LinkedList class which implements a Queue. The string is put into the queue one letter at a time. Then read back one letter at a time.

Code:
import java.util.*;
 
public class QueueExample {
   public static void main(String[] args) {
 
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter string: ");
      String str = sc.nextLine();
 
      Queue<Character> queue = new LinkedList<Character>();
 
      for(int i=0; i<str.length(); i++){
         queue.add(str.charAt(i));
      }
 
      String str2 = "";
      while( queue.peek() != null ){
        str2 = str2 + queue.remove(); 
        System.out.println(str2); 
      }
   }
}

Output:
$ java QueueExample
Enter string: ABCDEFGHIJ
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ