Level 3 - Stack

Another Java class that can hold many values is Stack. Stacks only allow you to add a new element (push) or retrieve the most recently added element (pop). This type of data structure is known as "last-in, first-out" or "LIFO".

Stack<String> namesStack = new Stack();
namesStack.push("Sarah");
namesStack.push("Ali");
namesStack.push("Joe");

String lastName = namesStack.pop(); //lastName will have the value "Joe"

Things to find out before you finish this module:

  • How to create and inititialize a Stack

  • How to push and pop items from a Stack

  • How to loop through all the elements of a Stack (advantages and disadvantages of different types of loop)

  • Advantages and disadvantages of Stacks
  • Sample Program

    StackDemo

    Student Recipes

    IntroToStack
    TextUndoRedo