πŸ“š Stack in Java – A Complete Beginner’s Guide (Part 2)

πŸ“¦ Stack Implementation Using Arrays (Push, Pop, Peek, isEmpty, isFull & Display)

Welcome to Part 2 of our Stack in Java series.

In Part 1, we learned:

  • βœ… What is a Stack?
  • βœ… LIFO (Last In, First Out)
  • βœ… Stack Terminologies
  • βœ… Push, Pop, Peek
  • βœ… Overflow & Underflow
  • βœ… Applications of Stack
  • βœ… Advantages & Disadvantages

Now it’s time to implement a Stack using Arrays.

This is the most common implementation used in schools, colleges, interviews, and competitive programming.

By the end of this tutorial, you’ll be able to build a complete Stack in Java from scratch.


πŸ“š Table of Contents

  1. Why Use Arrays?
  2. Stack Representation
  3. Stack Variables
  4. Creating a Stack
  5. Push Operation
  6. Pop Operation
  7. Peek Operation
  8. isEmpty()
  9. isFull()
  10. Display Stack
  11. Complete Java Program
  12. Dry Runs
  13. Time Complexity
  14. Common Mistakes
  15. FAQs
  16. Conclusion

πŸ€” Why Implement Stack Using Arrays?

An array is one of the easiest ways to implement a stack.

Advantages:

  • βœ… Simple to understand
  • βœ… Fast implementation
  • βœ… Direct indexing
  • βœ… Excellent performance

However,

Arrays have one limitation.

Their size is fixed.

Suppose

Size = 5

Once all five locations are occupied,

no additional element can be inserted.

This causes Stack Overflow.


🎨 Stack Representation

Suppose

Size = 5

Initially

Index

0

1

2

3

4

Array

[ ][ ][ ][ ][ ]

Top

-1

A value of -1 means

the stack is empty.


After pushing

10

20

30

Array

Index

0   1   2   3   4

10  20  30

Top

2

🧠 Understanding the Top Variable

The Top variable stores the index of the topmost element.

Initially

top = -1

Stack Empty


Push 10

top = 0

Push 20

top = 1

Push 30

top = 2

Current Stack

Top

↓

30

20

10

πŸ’» Creating a Stack

We need three variables.

int stack[];

int top;

int size;

stack[]

Stores all elements.


top

Stores the index of the top element.


size

Stores the maximum capacity.


πŸ’» Constructor

class Stack {

    int stack[];

    int top;

    int size;

    Stack(int size){

        this.size = size;

        stack = new int[size];

        top = -1;

    }

}

Initially

Top = -1

βž• Push Operation

Push means

Insert an element into the stack.

Example

Current

30

20

10

Push

40

Result

40

30

20

10

πŸ“ Algorithm

  1. Check Overflow.
  2. Increase Top.
  3. Store element.

🎨 Dry Run

Initially

Top = 2

Push

40

Increment

Top = 3

Store

stack[3] = 40

Done.


πŸ’» Java Program – Push

public void push(int value){

    if(top == size - 1){

        System.out.println("Stack Overflow");

        return;

    }

    top++;

    stack[top] = value;

}

βž– Pop Operation

Pop removes the top element.

Current

40

30

20

10

Pop

40

Result

30

20

10

πŸ“ Algorithm

  1. Check Underflow.
  2. Read top element.
  3. Decrease Top.

🎨 Dry Run

Current

Top = 3

Pop

40

Decrease

Top = 2

Done.


πŸ’» Java Program – Pop

public int pop(){

    if(top == -1){

        System.out.println("Stack Underflow");

        return -1;

    }

    int value = stack[top];

    top--;

    return value;

}

πŸ‘€ Peek Operation

Peek returns the top element

without removing it.

Current

40

30

20

10

Peek

40

Stack remains unchanged.


πŸ’» Java Program – Peek

public int peek(){

    if(top == -1){

        System.out.println("Stack is Empty");

        return -1;

    }

    return stack[top];

}

❓ isEmpty()

Checks whether the stack is empty.


πŸ’» Java Program

public boolean isEmpty(){

    return top == -1;

}

❓ isFull()

Checks whether the stack is full.


πŸ’» Java Program

public boolean isFull(){

    return top == size - 1;

}

πŸ“‹ Display Operation

Displays every element.

Always start from Top.

Current

40

30

20

10

Output

40

30

20

10

πŸ’» Java Program – Display

public void display(){

    if(top == -1){

        System.out.println("Stack is Empty");

        return;

    }

    for(int i = top; i >= 0; i--)

        System.out.println(stack[i]);

}

πŸ’» Complete Java Program

class Stack {

    int stack[];

    int top;

    int size;

    Stack(int size){

        this.size = size;

        stack = new int[size];

        top = -1;

    }

    public void push(int value){

        if(top == size - 1){

            System.out.println("Stack Overflow");

            return;

        }

        stack[++top] = value;

    }

    public int pop(){

        if(top == -1){

            System.out.println("Stack Underflow");

            return -1;

        }

        return stack[top--];

    }

    public int peek(){

        if(top == -1){

            System.out.println("Stack is Empty");

            return -1;

        }

        return stack[top];

    }

    public boolean isEmpty(){

        return top == -1;

    }

    public boolean isFull(){

        return top == size - 1;

    }

    public void display(){

        if(top == -1){

            System.out.println("Stack is Empty");

            return;

        }

        System.out.println("\nStack Elements:");

        for(int i = top; i >= 0; i--)

            System.out.println(stack[i]);

    }

    public static void main(String args[]){

        Stack s = new Stack(5);

        s.push(10);

        s.push(20);

        s.push(30);

        s.push(40);

        s.display();

        System.out.println("\nTop Element = " + s.peek());

        System.out.println("\nDeleted = " + s.pop());

        s.display();

        System.out.println("\nIs Empty? " + s.isEmpty());

        System.out.println("Is Full? " + s.isFull());

    }

}

Output

Stack Elements:

40
30
20
10

Top Element = 40

Deleted = 40

Stack Elements:

30
20
10

Is Empty? false

Is Full? false

πŸ“Š Time Complexity

OperationTime Complexity
PushO(1)
PopO(1)
PeekO(1)
isEmptyO(1)
isFullO(1)
DisplayO(n)

πŸ’Ύ Space Complexity

Suppose the stack contains n elements.

Memory required

O(n)

⚠️ Common Mistakes

❌ Forgetting Overflow Check

Never write

stack[++top] = value;

without checking

top == size - 1

Otherwise,

an ArrayIndexOutOfBoundsException may occur.


❌ Forgetting Underflow Check

Never perform

top--;

when

top == -1

❌ Starting Display from Index 0

Wrong

for(int i=0;i<=top;i++)

Although it prints all elements, it prints them from bottom to top.

A stack should be displayed from Top to Bottom.

Correct

for(int i=top;i>=0;i--)

❌ Initializing Top to 0

Wrong

top = 0;

Correct

top = -1;

❓ Frequently Asked Questions

Q1. Why is Top initialized to -1?

Because there are no elements initially.


Q2. Why is Push O(1)?

Only one element is inserted at the top.


Q3. Why is Pop O(1)?

Only the top element is removed.


Q4. What causes Stack Overflow?

Trying to insert into a full array-based stack.


Q5. What causes Stack Underflow?

Trying to remove an element from an empty stack.


Q6. What is the limitation of an array-based stack?

Its size is fixed and cannot grow dynamically.


🎯 Key Takeaways

  • πŸ“¦ Arrays provide a simple way to implement a Stack.
  • πŸ“ The Top variable keeps track of the current top element.
  • βž• Push inserts an element in O(1) time.
  • βž– Pop removes the top element in O(1) time.
  • πŸ‘€ Peek returns the top element without removing it.
  • ⚠️ Always check for Overflow and Underflow.
  • πŸ“‹ Display should always print elements from Top to Bottom.

πŸŽ‰ Conclusion

Implementing a Stack using Arrays is simple, efficient, and widely used in academic courses and programming interviews. The array-based implementation provides constant-time insertion and deletion at the top, making it an excellent choice when the maximum stack size is known in advance.

However, the major limitation of this approach is the fixed size of the array. If the stack becomes full, no additional elements can be inserted unless a larger array is created.

πŸ‘‰ In Part 3, we’ll overcome this limitation by implementing a Stack using a Linked List, where the stack grows dynamically without worrying about overflow due to fixed capacity. You’ll learn:

  • πŸ”— Stack using Linked List
  • πŸ“¦ Node Structure
  • βž• Push Operation
  • βž– Pop Operation
  • πŸ‘€ Peek Operation
  • ❓ isEmpty()
  • πŸ“‹ Display Operation
  • πŸ’» Complete Java Program
  • πŸ” Dry Runs
  • πŸ“ˆ Time Complexity Analysis
  • βš–οΈ Advantages over Array Implementation

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *