Technology6 min read

Stack Implementation in Java

Abhishek Ahlawat

By Abhishek Ahlawat — Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

#stack#java

Summarize this article using AI

Are you looking to understand the implementation of stack using arrays in Java?

Look no further! In this article, we will explore the ins and outs of this data structure, how it works, and the advantages of using this approach.

With a clear and engaging explanation of the implementation of stack using array in Java, you will have a better understanding of how to design and develop your own stack-based applications. So, let's dive in and explore the power of the implementation of stack using arrays in Java!

Implementation of Stack in Java

Implementation of Stack using Array

Although the use of all kinds of abstract data types such as Stack, Queue, and LinkedList is provided in Java it is always desirable to understand the basics of the data structure and implement it accordingly.
Please note that Stack Array's implementation is not dynamic. For the dynamic nature, one must use the LinkedList.

Stack Basic Operations

push:It is used to add the element to the top of the stack. The size of the stack will be increased by 1 with every added element.

pop: It is used to delete the element from the top of the stack and returns the deleted object. This size of the stack is decreased by 1 with every deleted element.

  • isEmpty: It is used to check if Stack is empty or not.
  • isFull: It is used to Check if Stack is full or not.
  • peek: It is the same as that of pop but it doesn't remove the top element and just returns it.

1. Implementation of Stack using Array in Java

import java.io.*;
import java.util.Scanner;
public class stack {
 static int ch;
 int element, maxsize, top;
 int[] st;
 public stack() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter stack size");
  maxsize = sc.nextInt();
  st = new int[maxsize];
  top = -1;
 }
 public void push(int element) {
  /*if(top>=maxsize)
{ System.out.println("Overflow!!");
//return(0);
}*/
  try {
   st[++top] = element;
  } catch (ArrayIndexOutOfBoundsException e) {
   System.out.println(e);
  }
 }
 public int pop() {
  if (top == -1) {
   System.out.println("UnderFlow");
   return (-1);
  }
  return (st[top--]);
 }

 public void display(int[] st, int max_size) {
  int i;
  System.out.println("Stack Elements:");
  for (i = 0; i <= max_size; i++)
   System.out.println(st[i]);
 }
}
public class myStack {
 static int ch;
 public static void main(String[] args) {
  stack obj = new stack();
  while (true) {
   System.out.println("\nEnter your choice\n1.PUSH\n2.POP\n3.Display\n4..EXIT");
   Scanner integer = new Scanner(System.in);
   ch = integer.nextInt();
   switch (ch) {
    case 1:
     System.out.println("Enter Element");
     obj.element = integer.nextInt();
     obj.push(obj.element);
     break;
    case 2:
     System.out.printf("Poped element is %d", obj.pop());
     break;
    case 3:
     obj.display(obj.st, obj.top);
     break;
    case 4:
     System.exit(0);
    default:
     System.out.println("Wrong option");
   }
  }
 }


Enter stack size
2
Enter your choice
1.PUSH
2.POP
3.Display
4..Exit
1
Enter Element
5
Enter your choice
1.PUSH
2.POP
3.Display
4..Exit
1
10
Enter your choice
1.PUSH
2.POP
3.Display
4..Exit
3
Stack Elements
5
10
Enter your choice
1.PUSH
2.POP
3.Display
4..Exit
2
Poped Element is 10

Stack Class in Java

Stack is a class within the Collection framework that extends the Vector class in Java. It also implements List, Collection, Iterable, Cloneable, and Serializable interfaces. It represents the LIFO object stack. Before using the Stack class, the java.util package must be imported. The stack class is arranged in the Collections framework's hierarchical structure.

Implementation of Stack using Stack Class

Java provides a Stack class that models the Stack data structure. The Stack class is part of Java’s collections framework. Following is the class hierarchy of Stack in Java -

Implementation of Stack

The Stack Class extend Vector which is a resizable collection that grows its size for the accommodation of new elements and shrinks itself when the elements are deleted. The Vector implements the List Interface.

There are five operations of Stack the class which is being extended from Vector class:

  • push(E item) – It is used to insert an element onto the top of the stack
  • pop() – It removes the element at the top of the stack and returns it as the value of the function
  • peek() –It is used to return the element at the top of the stack without removing it
  • empty() – It is a boolean function to test if the stack is empty or not.
  • search(Object ob) – This function looks for the object ob and returns its position. Returns 1 if found else return -1.

Let's take a look at how these five operations work:

Creation of Stack:

import java.util.*;

class Main {
  public static void main(String[] args) {
    Stack stack = new Stack();

Push operation:

// pushing integers onto the Stack
    stack.push(10);
    stack.push(20);

Pop operation:

System.out.println(stack.pop());
System.out.println(stack.pop());


20
10

IsEmpty operation:

while(!stack.isEmpty()) {
  System.out.println(stack.pop());
}


20
10

Peek operation:

System.out.println(stack.peek());


20

All the above functions can be used to implement the Stack Class in Java.

Conclusion:

With this, we have covered the Stack Data Structure in Java. We will be covering the other Data Structures too. Happy Learning. In this article, We learned about-

  • Implementation of Stack using Array
  • Implementation of Stack using Stack Class

If we missed any function, please do share it with us in the comment section.

Frequnetly Asked Questions(FAQs)

1. How would you implement a stack in C using an array?

Here is an example implementation of a stack using an array in C :

#define MAX_SIZE 100

int stack[MAX_SIZE];
int top = -1;

void push(int item) {
    if (top == MAX_SIZE - 1) {
        printf("Stack Overflow");
        return;
    }
    top++;
    stack[top] = item;
}

int pop() {
    int item;
    if (top == -1) {
        printf("Stack Underflow");
        return -1;
    }
    item = stack[top];
    top--;
    return item;
}

2. Which program implements a stack using array?

There are many programs that implement a stack using an array, but the specific implementation depends on the programming language and the requirements of the program. The example implementation above is one such program.

3. What is implementation of stack?

An implementation of a stack is a data structure that stores a collection of elements in a last-in, first-out (LIFO) order. The stack supports two main operations: push, which adds an element to the top of the stack, and pop, which removes the element from the top of the stack.

4. What are the advantages of implementing stack using array?

Some advantages of implementation of stack using array include:

  • Fast access to elements: Since an array provides constant time access to elements, pushing and popping elements from a stack implemented with an array is also fast.

  • Simple implementation: The implementation is relatively simple and easy to understand.

  • Memory efficiency: The use of an array means that there is no need for dynamic memory allocation, which can be memory intensive.

5. Can stacks be implemented using arrays only?

Yes, stacks can be implemented using arrays only. Other data structures such as linked lists can also be used, but using an array is a common and efficient way to implement a stack.

You may also like:

Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops — put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next