VOOZH about

URL: https://www.geeksforgeeks.org/java/stack-size-method-in-java-with-example/

⇱ Stack size() method in Java with Example - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:


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.


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.

Related Topics:

Comment