Printing the stack values in Java

In Java, I want to print the contents of a Stack. The toString() method prints them encased in square brackets delimited by commas: [foo, bar, baz].

How do I get rid of them and print the variables only?

My code so far:

Stack myStack = new Stack ();

for(int j=0; j<arrayForVar.length; j++) {
    if(arrayForVar[j][1] != null) {
        System.out.printf("%s \n", arrayForVar[j][1] + "\n");

System.out.printf("%s \n", myStack.toString());

This answer worked for me:

Use the toString method on the Stack, and use replaceAll method to replace all instances of square brackets with blankstring. Like this:

    myStack.toString().replaceAll("\\[", "").replaceAll("]", ""));

Leave a Comment