Donate HTML/CSS JavaFX Java Home
Array Data Structures Array List Data Structures Linked List Data Structures Stack Data Structures Queue Data Structures While Loops Do-While Loops For Loops For-each Loops If, Else, and Multi-Way If Statements Switch Statements Try-Catch Blocks Comment Types and Javadoc Java Classes Java Methods

Stack Data Structures

Code Description:

The Stack data structure should be used when elements that were last added need to be accessed first. Stacks can be thought of as a literal stack of boxes. The one on top is the one that was placed last. It is also the one that will need to be taken off first in order to access any other box. Interestingly, a Stack is not 0 based like an array. The top element has an index of 1. This has the opposite functionality of a Queue which implements a first in, first out (FIFO) implementation.

Stack Syntax:

Stack<String> stack = new Stack<String>();

Runnable Stack Example Code:

import java.util.Stack;

public class Demo {

    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
	stack.push("Stack Item 1");
	stack.push("Stack Item 2");
	stack.push("Stack Item 3");
	stack.push("Stack Item 4");
	stack.push("Stack Item 5");
	System.out.println("The index of \"Stack Item 1\" is: " +"Stack Item 1"));
	System.out.println("Removing the top element of: " + stack.pop());
	System.out.println("The top element is now: " + stack.peek());

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.


Stack Output Image

Important Methods:

  • peek() - returns the top element in the stack.
  • push() - adds a new element to the top of the stack.
  • pop() - removes and returns the top element of the stack.
  • search() - returns the position of a specified element in the stack.
  • empty() - returns true if the stack is empty.
  • clear() - removes all elements in the stack.

Related Links:

For-each Loops Queue Data Structures Array Data Structures Linked List Data Structures Array List Data Structures