What is the Stack.toString() method in Java?
Overview
The Stack class is a
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
Stackclass. -
Line 4: We create a new
Stackobject with the namestack. -
Lines 5 to 7: We add three elements (
1,2,3) to thestackobject using thepushmethod. -
Line 8: We use the
toStringmethod to get the string representation of thestack.