Skip to main content

Practical-33

Write a Java Program to implement the methods of Stack Class.

Introdution

A Stack is a Last-In-First-Out (LIFO) data structure. It is commonly used to store data in a program. The idea of a stack is to store elements such that when an element is added, the element added last is removed first. It is mainly used for storing and manipulating data. A Java Program can implement the methods of the Stack Class, so that elements can be added, modified, and removed from the Stack.

Code

import java.util.*;

public class StackExample {

public static void main(String[] args) {
//Creating an object of Stack class
Stack<String> stack = new Stack<String>();
//Using push() to insert elements in the stack
stack.push("This");
stack.push("is");
stack.push("a");
stack.push("stack");
stack.push("program");

//Display the stack
System.out.println("The elements of the stack are: "+stack);

//Using pop() to remove elements from the stack
System.out.println("Removing element with pop() function: "+stack.pop());

//Display the stack
System.out.println("The elements of the stack now are: "+stack);
}
}

Output

The elements of the stack are: [This, is, a, stack, program]
Removing element with pop() function: program
The elements of the stack now are: [This, is, a, stack]
Explanation

The code creates an object of the Stack Class and inserts elements into the stack using the push() method. It then displays the stack elements and then removes the last element using the pop() method. Finally, it displays the stack elements after removing the last element.