Computer Store
store.prestwood.com
-Collapse +Expand
Java
Search Java Group:

Advanced
-Collapse +Expand Java To/From
To/FromCODEGuides
-Collapse +Expand Java Store
PRESTWOODSTORE

Prestwood eMagazine

May Edition
Subscribe now! It's Free!
Enter your email:

   ► KBProgrammingJava   Print This     
Next Random Article Next Random Tidbit || Change Topic Random From All
  From the March 2016 Issue of Prestwood eMag
 
Stacks in Java
 
Posted 12 years ago on 6/30/2008
Take Away: Provides the definition of a stack and an example of its implementation in Java

KB101255

Question: What is a stack and how is it implemented in Java?

Answer:

A stack is a data structure that supports adding and removing of elements based on the last in, first out ordering. Adding elements is referred to as a push, while removing elements is referred to as a pop. Data that is pushed into a stack will be popped out in reverse order. For example, if a, b, c, and d are pushed into a stack. d, c, b, and then a will be popped out.

Other supported operations on stacks include:
empty(): tests if the stack is empty.
peek(): returns the object on the top of the stack without removing it from the stack.

import java.util.Stack;

public class Stacks
{
    public static void main(String[] args)
    {
        // Create a new stack
        Stack stk = new Stack();

        // Add items to stack
        stk.push("a");
        stk.push("b");
        stk.push("c");
        stk.push("d");

        // Remove elements until stack is empty
        while ( !stk.empty() )
        {
            System.out.print(stk.pop() + " ");
        }
    }
}

This code will print out "d c b a"

A stack is a data structure that supports adding and removing of elements based on the last in, first out ordering. Adding elements is referred to as a push, while removing elements is referred to as a pop. Data that is pushed into a stack will be popped out in reverse order. For example, if a, b, c, and d are pushed into a stack. d, c, b, and then a will be popped out.

More Info

Definition:  Stack

Comments

0 Comments.
Share a thought or comment...
 
Write a Comment...
...
Sign in...

If you are a member, Sign In. Or, you can Create a Free account now.


Anonymous Post (text-only, no HTML):

Enter your name and security key.

Your Name:
Security key = P1296A1
Enter key:
KB Post Contributed By Stephen Berry:
Visit Profile

 KB Article #101255 Counter
13092
Since 6/30/2008


©1995-2020 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech