Write a Java program to create a stack with hybrid items using Stack collection


The code is similar to the previous example, but there is a difference in the way the stack is declared and used.

  • The code starts by importing the necessary libraries: java.io.* and java.util.*.
  • The Hybrid_Item class is defined, serving as the entry point of the program.
  • In the main method, a new stack object named stck_list is created using the raw Stack class, without specifying the type of elements it will contain. In Java, it is recommended to use generics to specify the type of elements in a collection. Using raw types like Stack can lead to type safety issues.
  • The push method is used to add elements to the stack. Strings "Red," "Green," "Blue," "Yellow," and "Orange" are pushed onto the stack.
  • The System.out.println statement is used to print the contents of the stack. The stack is concatenated with the string "Stack Elements : " using the + operator. Since the stack is of a raw type, its toString method is called, which will provide a string representation of the stack.

Source Code

import java.io.*;
import java.util.*;
public class Hybrid_Item
{
	public static void main(String[] args)
	{
		Stack stck_list = new Stack();
		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]