DEV Community

Collins Kiplimo
Collins Kiplimo

Posted on

Java Stack: Unveiling LIFO Magic

A stack is a linear data structure that follows the principle of Last In First Out (LIFO). This means the last element inserted inside the stack is removed first.

Concepts and Principles:
Visualize a stack as a vertical arrangement of elements, where you can:

  • Push:
    Add an element to the top of the stack.

  • Pop:
    Remove an element from the top of the stack.

  • IsEmpty:
    Check if the stack is empty.

  • IsFull:
    Check if the stack is full.

  • Peek:
    View the value of the top element without removal.

Working of the Stack:
In Java programming, we use a pointer called top to keep track of the top element. Upon initialization, top is set to -1 to indicate an empty stack. When an element is pushed, top is incremented, and for popping, it is decremented. These operations are carried out with checks to avoid overflow or underflow.

Stack Implementation in Java:
Below is a practical implementation of a stack in Java:


public class Stack {
    private int maxSize;
    private int[] stackArray;
    private int top;

    public Stack(int size) {
        maxSize = size;
        stackArray = new int[maxSize];
        top = -1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == maxSize - 1;
    }

    public void push(int value) {
        if (!isFull()) {
            stackArray[++top] = value;
            System.out.println("Pushed item: " + value);
        } else {
            System.out.println("Stack is full. Cannot push.");
        }
    }

    public int pop() {
        if (!isEmpty()) {
            return stackArray[top--];
        } else {
            System.out.println("Stack is empty. Cannot pop.");
            return -1; 
        }
    }

    public int peek() {
        if (!isEmpty()) {
            return stackArray[top];
        } else {
            System.out.println("Stack is empty. Cannot peek.");
            return -1; 
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity:
Stack operations using arrays have a constant time complexity (O(1)) for both push and pop, making them efficient and suitable for various applications.

Applications:
Stacks prove their versatility across various domains:

  1. Expression Evaluation:
    Stacks assist compilers in evaluating expressions by converting them into postfix notation for efficient processing.

  2. Function Calls:
    Method calls and recursion in programming languages often utilize stacks to manage execution contexts.

  3. Browser History:
    Browsers utilize stacks to facilitate backward navigation through visited URLs.

Top comments (0)