Topics Index

QueueDemo - Java Example Program

class QueueDemo
    public static void main(String arg[])
        Queue<Integer> abq = new ArrayBlockingQueue<Integer>(3);
        System.out.println("Till now we have added 3 numbers");
        System.out.println("Now adding fourth element violating queue behaviour");
        System.out.println("Added fourth element : " + abq.offer(4)); // LINE A
        System.out.println("Elements in ArrayBlockingQueue : " + abq);
        abq.clear(); // Clears the elements in Queue // LINE B
        System.out.println("Remove first element : " + abq.poll()); // LINE C    

Till now we have added 3 numbers
Now adding fourth element violating queue behaviour
Added fourth element : false
Elements in ArrayBlockingQueue : [1, 2, 3]
Remove first element : null


In the above program we have created a ArrayBlockingQueue with the reference abq and restricted its capacityt to 3 and added three elements later at LINE A we tried to add fourth element using offer method which returned false since the capacity is restricted. At LINE B we have cleared the elements in the queue using clear method and tried to reomve the first element using poll method in the queue which returned false since the queue is empty

  • Replace the code at LINE A with the code below
    System.out.println("Added fourth element : " + abq.add(4));
    Since add method throws java.lang.IllegalStateException when the size of a ArrayBlockingQueue is violated.
  • Replace the code at LINE C with the code below
    System.out.println("Remove first element : " + abq.remove());
    Since remove method throws java.util.NoSuchElementException when an attempt is made to remove an element from an empty queue the above code throws a compilation error.

© meritcampus 2019

All Rights Reserved.

Open In App