The toString() method of Java Stack is used to return a string representation of the elements of the Collection.
The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation.
Syntax:
public String toString()
Parameter The method does not take any parameters.
Return This method returns a String representation of the collection.
Below examples illustrate the toString() method:
Example 1:
import java.util.*;
public class collection {
public static void main(String args[])
{
Stack<String> stack
= new Stack<String>();
stack.add( "Welcome" );
stack.add( "To" );
stack.add( "Geeks" );
stack.add( "For" );
stack.add( "Geeks" );
System.out.println(stack.toString());
}
}
|
Output:
[Welcome, To, Geeks, For, Geeks]
Example 2:
import java.util.*;
public class collection {
public static void main(String args[])
{
Stack<Integer> stack
= new Stack<Integer>();
stack.add( 10 );
stack.add( 20 );
stack.add( 30 );
stack.add( 40 );
System.out.println(stack.toString());
}
}
|
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
24 Dec, 2018
Like Article
Save Article