Write a Java program to create a stack using Stack collection


The code begins by importing the necessary libraries: java.io.* and java.util.*. These libraries provide classes and methods to work with input/output operations and data structures, respectively. The Create_Stack class is defined, which serves as the entry point of the program.

In the main method, a new stack object named stck_list is created using the Stack<String> class. This stack is intended to store strings. The push method is used to add elements to the stack. In this case, the strings "Red," "Green," "Blue," "Yellow," and "Orange" are pushed onto the stack one by one.

After pushing the elements onto the stack, the System.out.println statement is used to print the contents of the stack. The string representation of the stack is obtained using the toString method, which is implicitly called when concatenating the stack with a string.

Source Code

import java.io.*;
import java.util.*;
public class Create_Stack
{
	public static void main(String[] args)
	{
		Stack < String > stck_list = new Stack < String > ();
		stck_list.push("Red");
		stck_list.push("Green");
		stck_list.push("Blue");
		stck_list.push("Yellow");
		stck_list.push("Orange");
 
		System.out.println("Stack Elements : " + stck_list);
	}
}

Output

Stack Elements : [Red, Green, Blue, Yellow, Orange]