Difference between Stack and Queue Data Structure in Java

Diep Thanh Tu
3 min readJan 29, 2019

--

Stack and Queue are two of important data structures in the programming world and have a variety of usage. As opposed to the array and linked list, which are considered as a primary data structure, they are a secondary data structure which can build using an array or linked list.

You can use Stack to solve recursive problems and Queue can be used for ordered processing

Stack is LIFO (last In First Out) data structure which means the item which is inserted last is retrieved first, similar to a stack of plates in a dinner party, where every guest pick up the plate from the top of stack.
On the other hand, Queue data structure literally represent a queue, which is a FIFO (First In First Out) data structure, i.e. object which is first inserted, is first consumed

Now let’s see differences between Stack and Queue data structure in Java:

1) The first and major difference between Stack and Queue data structure is that Stack is LIFO(Last In First Out) data structure while Queue is FIFO (First In First out) data structure. So if you have a requirement where elements are processed in the order they are generated or put into Queue, you should use a Queue implementation, which supports FIFO ordering, but if you need to work with the most recently added entry, Stack would be the right data structure.

2) Key operation supported by any Stack implementation are push() and pop() which is used to add and retrieve an element from Stack, worth noting is that pop() not only retrieves element but also removes it from Stack.

The key operation for Queue data structure in Java is offer() and poll(), which is used to add an object into Queue and retrieve an object from the head of Queue. Though Queue also supports add(Object o)and remove(Object o) operation, inherited from Collection, there is the difference between them. Collection method throws Exception, while Queue methods return special values e.g. null, in exceptional cases.

For example offer() return false, if it’s not able to insert an element into Queue, while add() throws a RuntimeException when it fails to add an element into Queue. Similarly poll() returns null if the queue is empty, while remove method throws an unchecked exception.

3) An example of using Stack data structure is reversing a String in Java, you can reverse a String by simply putting each character from String into Stack and once you finished, start popping them up. Since Stack is LIFO data structure, you will retrieve letters in reverse order.

A good example of Queue is a producer-consumer problem, in which producer produces and consumer consumes the item. This problem also helps to understand BlockingQueue, which is a relatively new concurrent utility, which can simplify producer-consumer designs in concurrent programs.

refer to Javarevisited

--

--