Java Program to Implement Stack

«
»
This is a Java Program to implement a stack. Stack is an area of memory that holds all local variables and parameters used by any function and remembers the order in which functions are called so that function returns occur correctly. ‘push’ operation is used to add an element to stack and ‘pop’ operation is used to remove an element from stack. ‘peek’ operation is also implemented returning the value of the top element without removing it. The relation between the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure. The implemented stack has bounded capacity.

Here is the source code of the Java program to implement a stack. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  * Java Program to Implement Stack
  3.  */
  4.  
  5. import java.util.*;
  6.  
  7. /*  Class arrayStack  */
  8. class arrayStack
  9. {
  10.     protected int arr[];
  11.     protected int top, size, len;
  12.     /*  Constructor for arrayStack */
  13.     public arrayStack(int n)
  14.     {
  15.         size = n;
  16.         len = 0;
  17.         arr = new int[size];
  18.         top = -1;
  19.     }
  20.     /*  Function to check if stack is empty */
  21.     public boolean isEmpty()
  22.     {
  23.         return top == -1;
  24.     }
  25.     /*  Function to check if stack is full */
  26.     public boolean isFull()
  27.     {
  28.         return top == size -1 ;        
  29.     }
  30.     /*  Function to get the size of the stack */
  31.     public int getSize()
  32.     {
  33.         return len ;
  34.     }
  35.     /*  Function to check the top element of the stack */
  36.     public int peek()
  37.     {
  38.         if( isEmpty() )
  39.             throw new NoSuchElementException("Underflow Exception");
  40.         return arr[top];
  41.     }
  42.     /*  Function to add an element to the stack */
  43.     public void push(int i)
  44.     {
  45.         if(top + 1 >= size)
  46.             throw new IndexOutOfBoundsException("Overflow Exception");
  47.         if(top + 1 < size )
  48.             arr[++top] = i;
  49.         len++ ;
  50.     }
  51.     /*  Function to delete an element from the stack */
  52.     public int pop()
  53.     {
  54.         if( isEmpty() )
  55.             throw new NoSuchElementException("Underflow Exception");
  56.         len-- ;
  57.         return arr[top--]; 
  58.     }    
  59.     /*  Function to display the status of the stack */
  60.     public void display()
  61.     {
  62.         System.out.print("\nStack = ");
  63.         if (len == 0)
  64.         {
  65.             System.out.print("Empty\n");
  66.             return ;
  67.         }
  68.         for (int i = top; i >= 0; i--)
  69.             System.out.print(arr[i]+" ");
  70.         System.out.println();
  71.     }    
  72. }
  73.  
  74. /*  Class StackImplement  */
  75. public class StackImplement
  76. {
  77.     public static void main(String[] args)
  78.     {
  79.         Scanner scan = new Scanner(System.in);        
  80.         System.out.println("Stack Test\n");
  81.         System.out.println("Enter Size of Integer Stack ");
  82.         int n = scan.nextInt();
  83.         /* Creating object of class arrayStack */
  84.         arrayStack stk = new arrayStack(n);
  85.         /* Perform Stack Operations */
  86.         char ch;
  87.         do{
  88.             System.out.println("\nStack Operations");
  89.             System.out.println("1. push");
  90.             System.out.println("2. pop");
  91.             System.out.println("3. peek");
  92.             System.out.println("4. check empty");
  93.             System.out.println("5. check full");
  94.             System.out.println("6. size");
  95.             int choice = scan.nextInt();
  96.             switch (choice)
  97.             {
  98.             case 1 : 
  99.                 System.out.println("Enter integer element to push");
  100.                 try 
  101.                 {
  102.                     stk.push( scan.nextInt() );
  103.                 }
  104.                 catch (Exception e)
  105.                 {
  106.                     System.out.println("Error : " + e.getMessage());
  107.                 }                         
  108.                 break;                         
  109.             case 2 : 
  110.                 try
  111.                 {
  112.                     System.out.println("Popped Element = " + stk.pop());
  113.                 }
  114.                 catch (Exception e)
  115.                 {
  116.                     System.out.println("Error : " + e.getMessage());
  117.                 }    
  118.                 break;                         
  119.             case 3 :         
  120.                 try
  121.                 {
  122.                     System.out.println("Peek Element = " + stk.peek());
  123.                 }
  124.                 catch (Exception e)
  125.                 {
  126.                     System.out.println("Error : " + e.getMessage());
  127.                 }
  128.                 break;                         
  129.             case 4 : 
  130.                 System.out.println("Empty status = " + stk.isEmpty());
  131.                 break;                
  132.             case 5 :
  133.                 System.out.println("Full status = " + stk.isFull());
  134.                 break;                 
  135.             case 6 : 
  136.                 System.out.println("Size = " + stk.getSize());
  137.                 break;                         
  138.             default : 
  139.                 System.out.println("Wrong Entry \n ");
  140.                 break;
  141.             }
  142.             /* display stack */
  143.             stk.display();            
  144.             System.out.println("\nDo you want to continue (Type y or n) \n");
  145.             ch = scan.next().charAt(0);
  146.  
  147.         } while (ch == 'Y'|| ch == 'y');                 
  148.     }
  149. }

advertisement
Stack Test
 
Enter Size of Integer Stack
5
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
4
Empty status = true
 
Stack = Empty
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
1
Enter integer element to push
24
 
Stack = 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
1
Enter integer element to push
6
 
Stack = 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
1
Enter integer element to push
162
 
Stack = 162 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
1
Enter integer element to push
19
 
Stack = 19 162 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
1
Enter integer element to push
94
 
Stack = 94 19 162 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
5
Full status = true
 
Stack = 94 19 162 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
1
Enter integer element to push
32
Error : Overflow Exception
 
Stack = 94 19 162 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
3
Peek Element = 94
 
Stack = 94 19 162 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
2
Popped Element = 94
 
Stack = 19 162 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
2
Popped Element = 19
 
Stack = 162 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
2
Popped Element = 162
 
Stack = 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
6
Size = 2
 
Stack = 6 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
2
Popped Element = 6
 
Stack = 24
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
2
Popped Element = 24
 
Stack = Empty
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
2
Error : Underflow Exception
 
Stack = Empty
 
Do you want to continue (Type y or n)
 
y
 
Stack Operations
1. push
2. pop
3. peek
4. check empty
5. check full
6. size
 
4
Empty status = true
 
Stack = Empty
 
Do you want to continue (Type y or n)
 
n

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.