What is stack.size() in Java?

The stack.size() function in Java returns the number of elements in the stack. In short, this function is used to get the current size of the stack.

The following illustration shows a visual representation of the stack.size() function.

A visual representation of the stack.size() function

The java.util.* module is required in order to use this function.

Syntax

stack_name.size();
// where the stack_name is the name of the stack

Parameter

The stack.size() function does not require any parameters.

Return value

This function returns the number of elements in the stack.

Code

import java.util.*;
class JAVA {
public static void main( String args[] ) {
Stack<Integer> Stack = new Stack<Integer>();
Stack.add(0);
Stack.add(2);
Stack.add(5);
Stack.add(3);
Stack.add(1);
System.out.println("The following are the elements in the stack: " + Stack);
System.out.println("The following is the size of the stack: " + Stack.size());
}
}