Share
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
.
The syntax of the toString
method is given below:
public String toString()
This method doesn’t take any argument.
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.
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
.