ArrayBlockingQueue toString() Method in Java


The toString() method in Java is used to return a string representation of the object. In the case of ArrayBlockingQueue, the toString() method returns a string representation of the elements in the queue.

Syntax:

public String toString()

Example:

import java.util.concurrent.ArrayBlockingQueue;

public class Main {
  public static void main(String[] args) {
    ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);
    queue.add(1);
    queue.add(2);
    queue.add(3);
    queue.add(4);
    queue.add(5);
    System.out.println(queue.toString());
  }
}

Output:

[1, 2, 3, 4, 5]

In the above example, we have created an ArrayBlockingQueue of size 5 and added 5 elements to it. The toString() method is then called on the queue object, which returns a string representation of the elements in the queue. The output shows the elements in the queue enclosed in square brackets and separated by commas.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.