What is the Stack.toString() method in Java?

Overview

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

The toString() method will return the String representation of the Stack object. It also returns the String representation of each element in the stack.

Syntax

The syntax of the toString method is given below:

public String toString()

Parameter(s)

This method doesn’t take any argument.

Return value

This method returns a String as a result. The returned String contains the elements of the stack in the insertion order enclosed between the brackets [] and separated by commas (,). Internally, the elements are converted to string using the String.valueOf(Object) method.

Code

import java.util.Stack;
class ToString {
public static void main( String args[] ) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.toString());
}
}

In the code above,

  • Line 1: We imported the Stack class.

  • Line 4: We create a new Stack object with the name stack.

  • Lines 5 to 7: We add three elements (1,2,3) to the stack object using the push method.

  • Line 8: We use the toString method to get the string representation of the stack.

Free Resources