Java Stack - size() Method
The java.util.Stack.size() method returns the number of elements in the stack.
Syntax
public int size()
Parameters
No parameter is required.
Return Value
Returns the number of elements in the stack.
Exception
NA
Example:
In the example below, the java.util.Stack.size() method is used to find out the number of elements in the stack.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a stack Stack<Integer> MyStack = new Stack<Integer>(); //populating stack MyStack.push(10); MyStack.push(20); MyStack.push(30); System.out.println("Size of MyStack: " + MyStack.size()); //adding one more element in the stack System.out.println(MyStack.push(40) + " is added in MyStack."); System.out.println("Now, Size of MyStack: " + MyStack.size()); } }
The output of the above code will be:
Size of MyStack: 3 40 is added in MyStack. Now, Size of MyStack: 4
❮ Java.util - Stack