Monday, December 22, 2025
HomeLanguagesJavaStack toString() method in Java with Example

Stack toString() method in Java with Example

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:




// Java program to demonstrate
// Stack toString() method
  
import java.util.*;
  
public class collection {
    public static void main(String args[])
    {
        // Creating an Empty Stack
        Stack<String> stack
            = new Stack<String>();
  
        // Use add() method
        // to add elements to the Collection
        stack.add("Welcome");
        stack.add("To");
        stack.add("Geeks");
        stack.add("For");
        stack.add("Geeks");
  
        // Using toString() method
        System.out.println(stack.toString());
    }
}


Output:

[Welcome, To, Geeks, For, Geeks]

Example 2:




// Java program to demonstrate
// Stack toString() method
  
import java.util.*;
  
public class collection {
    public static void main(String args[])
    {
        // Creating an Empty Stack
        Stack<Integer> stack
            = new Stack<Integer>();
  
        // Use add() method
        // to add elements to the Collection
        stack.add(10);
        stack.add(20);
        stack.add(30);
        stack.add(40);
  
        // Using toString() method
        System.out.println(stack.toString());
    }
}


Output:

[10, 20, 30, 40]
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32455 POSTS0 COMMENTS
Milvus
111 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11958 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12038 POSTS0 COMMENTS
Shaida Kate Naidoo
6958 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6911 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS