Stack Using Array And Class Example Java Program


Definition

A stack is a basic computer science data structure and can be defined in an abstract, implementation-free manner, or it can be generally defined as a linear list of items in which all additions and deletion are restricted to one end that is Top.

Stack Using Array And Class Example Program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Stack {

    private int top;
    private int item[];

    Stack(int size) {
        top = -1;
        item = new int[size];
    }

    void pushItem(int data) {
        if (top == item.length - 1) {
            System.out.println("Stack is Full");
        } else {
            item[++top] = data;
            System.out.println("Pushed Item :" + item[top]);
        }
    }

    int popItem() {
        if (top < 0) {
            System.out.println("Stack Underflow");
            return 0;
        } else {
            System.out.println("Pop Item : " + item[top]);
            return item[top--];
        }
    }
}

class StackExample {

    public static void main(String[] args) throws IOException {
        Stack stk = new Stack(5);
        boolean yes=true;
        int choice;
        BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
        
        do{
            System.out.println("1).Push\n2).Pop\n3).Exit\n\nEnter Choice");
            choice = Integer.parseInt(is.readLine());
            
            switch(choice)
            {
                case 1: System.out.println("Enter Push Item: ");
                        stk.pushItem(Integer.parseInt(is.readLine()));
                        break;
                case 2: stk.popItem();break;
                case 3: yes = false;break;
                default: System.out.println("Invalid Choice");
            }
        }while(yes==true);
        
    }
}

Sample Output

Output is:
1).Push
2).Pop
3).Exit

Enter Choice
1
Enter Push Item: 
14
Pushed Item :14
1).Push
2).Pop
3).Exit

Enter Choice
1
Enter Push Item: 
567
Pushed Item :567
1).Push
2).Pop
3).Exit

Enter Choice
1
Enter Push Item: 
67
Pushed Item :67
1).Push
2).Pop
3).Exit

Enter Choice
1
Enter Push Item: 
789
Pushed Item :789
1).Push
2).Pop
3).Exit

Enter Choice
1
Enter Push Item: 
56
Pushed Item :56
1).Push
2).Pop
3).Exit

Enter Choice
1
Enter Push Item: 
99
Stack is Full
1).Push
2).Pop
3).Exit

Enter Choice
2
Pop Item : 56
1).Push
2).Pop
3).Exit

Enter Choice
2
Pop Item : 789
1).Push
2).Pop
3).Exit

Enter Choice
2
Pop Item : 67
1).Push
2).Pop
3).Exit

Enter Choice
2
Pop Item : 567
1).Push
2).Pop
3).Exit

Enter Choice
2
Pop Item : 14
1).Push
2).Pop
3).Exit

Enter Choice
2
Stack Underflow
1).Push
2).Pop
3).Exit

Enter Choice
3