Java Program to demonstrate stack class in Collection framework
Program
package stackPack;
import java.util.*;
public class StackCollectionDemo
{
public static void main(String[] args)
{
Stack st = new Stack();
System.out.println("Contents of stack:\t" + st);
System.out.println("Is stack empty?:\t" + st.empty());
st.push(15);
st.push(25);
st.push(35);
st.push(45);
System.out.println("Contents of stack:\t" + st);
System.out.println("Index of searched element (15):\t" + st.search(15));
System.out.println("Top of the stack is:\t" + st.peek());
st.pop();
st.pop();
System.out.println("Contents after pop operation:\t" + st);
}
}
This Java program demonstrates the use of the Stack
class from the Java Collection Framework.
-
Stack
Class:- The
Stack
class in Java provides a last-in-first-out (LIFO) data structure. - It is a part of the
java.util
package and extendsVector
.
- The
-
Program Workflow:
- Initialization: Creates an empty
Stack
object namedst
. - Checking Empty Stack: Uses the
empty()
method to check if the stack is empty. - Push Operation:
- Adds elements (
15
,25
,35
,45
) to the stack using thepush()
method.
- Adds elements (
- Display Contents: Prints the contents of the stack after push operations.
- Search Operation: Uses the
search()
method to find the position of an element (15
) in the stack. - Peek Operation: Uses the
peek()
method to display the top element of the stack without removing it. - Pop Operation:
- Removes the top elements of the stack using the
pop()
method. - Prints the updated stack contents after popping elements.
- Removes the top elements of the stack using the
- Initialization: Creates an empty
-
Output Messages:
- Provides information about the stack contents, whether it's empty, the top element, and the result of the search.
-
Key Methods of
Stack
Used:push(E element)
: Adds an element to the top of the stack.pop()
: Removes and returns the top element of the stack.peek()
: Returns the top element without removing it.empty()
: Checks if the stack is empty.search(Object o)
: Returns the 1-based position of the element from the top of the stack. If not found, it returns-1
.
Output
$ javac -d . StackCollectionDemo.java
$ java stackPack.StackCollectionDemo
Contents of stack: []
Is stack empty?: true
Contents of stack: [15, 25, 35, 45]
Index of searched element (15): 4
Top of the stack is: 45
Contents after pop operation: [15, 25]