Programming Examples

Java program to implement stack and its operation


Java Program to implement the Stack using array.

Solution

import java.util.*;
class Stack
{
    int stack[]=new int[10];
    int top=-1;
    void push(int num)
    {
        if(top>=9)
        {
            System.out.println("Stack is OverFlow");
        }
        else
        {
            top++;
            stack[top]=num;
        }
    }
    void pop()
    {
        if(top==-1)
        {
            System.out.println("Stack is Empty");
        }
        else
        {
            System.out.println("Poped Element is "+stack[top]);
            top--;
        }
    }
    public static void main(String arr[])
    {
        Stack obj=new Stack();
        Scanner sc=new Scanner(System.in);
        int ch,n;
        do
        {
            System.out.println("1.Push\n2.Pop\n0.Exit\nEnter any Choice :");
            ch=sc.nextInt();
            switch(ch)
            {
                case 1:
                    System.out.println("Enter the Data Item : ");
                    n=sc.nextInt();
                    obj.push(n);
                break;
                case 2:
                    obj.pop();
                break;
                case 0:
                    System.exit(0);
                break;
                default:
                    System.out.println("Invalid Choice ");
            }
            
        }while(ch!=0);
    }
}
Output

1.Push

2.Pop

0.Exit

Enter any Choice :

1

Enter the Data Item : 

34

1.Push

2.Pop

0.Exit

Enter any Choice :

1

Enter the Data Item : 

56

1.Push

2.Pop

0.Exit

Enter any Choice :

1

Enter the Data Item : 

44

1.Push

2.Pop

0.Exit

Enter any Choice :

2

Poped Element is 44

1.Push

2.Pop

0.Exit

Enter any Choice :

2

Poped Element is 56

1.Push

2.Pop

0.Exit

Enter any Choice :

2

Poped Element is 34

1.Push

2.Pop

0.Exit

Enter any Choice :

2

Stack is Empty

1.Push

2.Pop

0.Exit

Enter any Choice :

2

Stack is Empty

1.Push

2.Pop

0.Exit

Enter any Choice :

1

Enter the Data Item : 

40

1.Push

2.Pop

0.Exit

Enter any Choice :

1

Enter the Data Item : 

60

1.Push

2.Pop

0.Exit

Enter any Choice :

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz