Java Program to Traverse a Stack Collection Using the ‘Foreach’ Loop

You are currently viewing Java Program to Traverse a Stack Collection Using the ‘Foreach’ Loop

Java program to traverse a Stack collection using the ‘foreach’ loop

// Java program to travers a Stack collection 
// using "foreach" loop

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String[] args) {
    Stack < Integer > stack = new Stack < Integer > ();

    stack.push(10);
    stack.push(20);
    stack.push(30);
    stack.push(40);

    System.out.println("Stack items: ");
    for (int val: stack) {
      System.out.println(val);
    }
  }
}

Output

Stack items: 
10
20
30
40

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply