Write a Java program to traverse a Stack collection using the foreach loop


The code demonstrates the usage of a foreach loop to iterate over the elements of a stack in Java. Let's go through the code step by step:

  • The code starts by importing the necessary libraries: java.io.* and java.util.*.
  • The Foreach_Loop class is defined, serving as the entry point of the program.
  • In the main method, a new stack object named stack_list is created using generics. It is specified that the stack will contain elements of type Integer.
  • Several integers, from 10 to 100 in increments of 10, are pushed onto the stack using the push method.
  • The System.out.println statement is used to print the string "Stack Items : ".
  • A foreach loop is used to iterate over the elements of the stack. The loop variable val represents each element in the stack, and for each iteration, it is printed using the System.out.println statement.

Source Code

import java.io.*;
import java.util.*;
public class Foreach_Loop
{
	public static void main(String[] args)
	{
		Stack < Integer > stack_list = new Stack < Integer > ();
		stack_list.push(10);
		stack_list.push(20);
		stack_list.push(30);
		stack_list.push(40);
		stack_list.push(50);
		stack_list.push(60);
		stack_list.push(70);
		stack_list.push(80);
		stack_list.push(90);
		stack_list.push(100);
 
		System.out.println("Stack Items : ");
		for (int val: stack_list)
		{
			System.out.println(val);
		}
	}
}

Output

Stack Items :
10
20
30
40
50
60
70
80
90
100