Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the ArrayBlockingQueue.toString method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

ArrayBlockingQueue is a bounded, thread-safe queue that uses a fixed-size array. This means that once the object is created, the size cannot be changed. The elements of this queue follow First-In-First-OutElements are inserted at the end of the queue and retrieved from the head of the queue. null objects are not allowed as elements.

The toString method can be used to get a String representation of the ArrayBlockingQueue object.

Syntax

public String toString()

Parameters

This method doesn’t take any parameters.

Return value

The toString method returns the String representation of the queue object.

  • The elements are enclosed within square brackets [].

  • Each element is separated by a comma ,.

  • Each element is converted to a string with the String.valueOf(Object) method.

  • The elements of the queue are in the order as returned by the iterator.

Code

The code below demonstrates how to use the toString method.

import java.util.concurrent.ArrayBlockingQueue;
class ToString {
public static void main( String args[] ) {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
queue.add("1");
queue.add("2");
queue.add("3");
System.out.println(queue.toString());
}
}

Explanation

In the code above:

  • In line 1, import ArrayBlockingQueue from the java.util.concurrent package.

  • In line 4, create an object for the ArrayBlockingQueue class with the name queue and size 5.

  • In lines 5 to 6, use the add method to add three elements to the queue object.

  • In line 8, use the toString method to get the string representation of the queue object.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring