Stack Program in Java
Stack Program in Java
The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector class. It implements the stack data structure that works on LIFO (Last In First Out) principle. The stack program in Java shows the usage of the stack in the program.
Syntax to Create a Stack
1
2
3
Stack<type> identifier = new Stack<type>();
type is the kind of object we are going to create, and identifier is the reference variable.
Adding Elements to the Stack
In order to add elements to the stack, the push() method is invoked. Consider the following program.
FileName: StackExample.java
// Importing the class Stack
import java.util.Stack;
public class StackExample
{
// driver method
public static void main(String argvs[])
{
// creating an object of the class Stack
Stack<Integer> stk = new Stack<Integer>();
// adding elements to the stack
// stk contains 9
stk.push(9);
// stk contains 9, 5
stk.push(5);
// stk contains 9, 5, 7
stk.push(7);
// stk contains 9, 5, 7, 14
stk.push(14);
// stk contains 9, 5, 7, 14, 29
stk.push(29);
// caculating size of the stack
int size = stk.size();
// displaying the stack on the console
System.out.println(“The size of the stack is: “ + size);
System.out.println(“The stack contains: “ + stk);
}
}