Skip to content


Stacks in java

In this article we’ll discuss stack in java.

What is stack?

Stack allows access to only one data item at a time. If you remove this item, then you can acess next-to-last item inserted, and so on. Stacks are very useful in many programming situations. It is used to solve certain complex data structure problems. Most of the microsprocesors use stack for their operation. The stack class is built on the vector class, and it implements a stack construct.  

When we’re working with stacks, we use push() and pop() methods add and retrieve elements from it. Elements come off a stack in reverse order in which they were added to it. 

Example of Stack

 
 import java.util.*;
 
 class stack
 
{
 
public static void main(String args[])
 
{
 
Stack< integer > s1= new Stack< Integer >(); 
 
try
 
{
 
s1.push(new Integer(0));
 
s1.push(new Integer(1));
 
s1.push(new Integer(2));
 
s1.push(new Integer(3));
 
System.out.println((Integer) s1.pop());
 
System.out.println((Integer) s1.pop());
 
System.out.println((Integer) s1.pop());
 
System.out.println((Integer) s1.pop());
 
}
 
catch(EmptyStackException e) { } 
 
}
 
}

Output : 3 2 1 0
Code Explaination:

Here, we are using push() method to add values on stack and pop() method to retrieve the elements from it. For stack related problem we have “emptystackexception”, that we’re catching in our program. 

Hope above information helps. If you’ve any questions related with stack then please feel free to say it in comments.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.