How to Print Stack in Java

Rashmi Patidar Feb 02, 2024
How to Print Stack in Java

The stack is a data structure that allows the users to add elements in the Last In First Out pattern. The elements get added to a collection that the first inserted element comes out in the last. The collection is represented by the Stack class in Java from the java.util package.

Below is the code block to explain the printing of stack values.

import java.util.Arrays;
import java.util.Stack;

public class PrintStackJava {
  public static void main(String[] args) {
    Stack stack = new Stack();
    for (int i = 0; i < 10; i++) {
      stack.push(i);
    }
    System.out.println(stack);
    System.out.println(Arrays.asList(stack));
  }
}

In the above code block, a stack instance gets created using a new keyword. The for loop gets formed to fill up the stack. The conditional loop runs 10 times starting from the 0 to 9 value. The stack operation push inserts the values in the stack. The method push hence fills the stack with the integer values. The method adds the element to the top of the stack type. The function adds the values in the stack, and for printing the values, the below-mentioned functions can get used.

The way includes simple printing of elements using the system’s println method. The println function takes the Object instance and is not of a specific class. It can be any class instance present in Java. So, the method prints the stack values.

Another way to print is using the Arrays.asList function. The static method is present in the Arrays class and does take the generic instance type. The method prints the list in the console output. Hence the stack values visible in the console output has two square brackets. The stack instance prints a list that gets wrapped with the print stream function.

The output of the above code block is below.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
Rashmi Patidar avatar Rashmi Patidar avatar

Rashmi is a professional Software Developer with hands on over varied tech stack. She has been working on Java, Springboot, Microservices, Typescript, MySQL, Graphql and more. She loves to spread knowledge via her writings. She is keen taking up new things and adopt in her career.

LinkedIn

Related Article - Java Stack