Stack size() method in Java with Example

Last Updated : 26 Dec, 2025

The size() method of java.util.Stack is used to get the number of elements present in the stack. It does not take any parameters and returns an int representing the stack's size.

Example:

Java
import java.util.*;
public class GFG {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.add("Welcome");
        stack.add("To");
        stack.add("GFG");
        
        System.out.println("Stack: " + stack);
        System.out.println("The size is: " + stack.size());
    }
}

Output
Stack: [Welcome, To, GFG]
The size is: 3

Explanation:

  • A Stack of Integers is created using Stack<Integer> stack = new Stack<>().
  • Elements are added to the stack using add().
  • stack.size() returns 3, which is the number of elements currently in the stack.

Syntax

int size()

Example: This code demonstrates how to use the size() method of the Stack class in Java to find the number of elements present in a stack of integers.

Java
import java.util.*;
public class GFG {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.add(10);
        stack.add(15);
        stack.add(30);
        stack.add(20);
        stack.add(5);
        System.out.println("Stack: " + stack);
        System.out.println("The size is: " + stack.size());
    }
}

Output
Stack: [10, 15, 30, 20, 5]
The size is: 5

Explanation: stack.size() returns the total number of elements in the stack and prints it.

Comment