Java stack class example

Problem

Write a Java class to implement a stack data structure using an array for storage. The stack must support pop and push operations.

Java stack class example

Java stack implementation

A stack is a LIFO (last in first out) data structure. A push operation adds an element to the top of the stack. On the other hand a pop operation deletes an element from the top of the stack. We can use a regular array to store the stack elements. Whenever we push to the stack we fill the next available position in the array. Whenever we pop from the stack we mark the last filled position as free. We need to check if the stack is full before we push a new element. We also need to make sure the stack is not empty before a pop operation.

Java stack source code

Here is a suggested solution in Java. The following is the source code of the Java Class followed by the driver main program. If you want to copy the source code please put each one into a separate source code file. The first code snippet should be saved into JavaStack.java and the second code snippet should be saved into TestStack.java

I hope this was a useful tutorial, if you have questions or comments please use the comments section below. Thanks for reading.

Tags:,

Add a Comment

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