Stack (Implementation)

How is Stack implemented in Java? What are some of the main methods that each stack have? That is what we are going to cover in this lesson.

Introduction

Every programming language comes with the basic functionality of Stack. In Java, you can use the pre-built class of Stack by importing it to your program. However, you can manually implement a stack and extend its functionality for your use.

Stacks can either be implemented using arrays or linked lists. It has yet to be concluded which implementation is more efficient, as both data structures offer different variations of Stack. However, stacks are generally implemented using arrays because it takes less space; we don’t need to store an additional pointer like in a linked list.

Implementation

A typical Stack must contain the following standard methods:

  • push (datatype V)
  • datatype pop()
  • boolean isEmpty()
  • datatype top()

Before we take a look at these methods one by one, let’s construct a class of Stack, and create an instance. This class has the following three data members:

  • the array that will hold all the elements
  • the size of this array
  • a variable for the top element of Stack.

The following code shows how to construct the Stack class:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.