Using a Stack



This example shows how to use the Stack class. A Stack adds and removes elements on a First-In First-Out basis.
The key methods of the Stack class are push(), peek(), pop(), empty() and search().

push() – adds an element to the top of the stack.
peek() – returns the first element from the top of the stack without removing it from the stack.
pop() – as peek() but removes it from the stack.
empty() – checks wheter there are elements in the stack or not.
search() – returns the position of an element in the stack.

Now we have two elements in the stack, and to check what element is at the top of the stack (and will be the first to be removed) we use the peek() method to find out.

The output is:

To find out the position of the first element, we use the method search().

This will print out the position within the stack.

To remove elements from the stack, we use the method pop().

This will result in the output:

The ‘element 2′ was added after ‘element 1′ so that element is removed first.
Now the stack is empty, and to be sure we check with the empty method:







Search for more Java info on this site here:
Custom Search


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">