Java Utility Library

Java Stack - capacity() Method



The java.util.Stack.capacity() method returns the current capacity of the stack.

Syntax

public int capacity()

Parameters

No parameter is required.

Return Value

Returns the current capacity of the stack (the length of its internal data array, kept in the field elementData of this stack).

Exception

NA.

Example:

In the example below, the java.util.Stack.capacity() method is used to find out the current capacity of 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);
    MyStack.push(40);
    MyStack.push(50);

    System.out.println("Size of MyStack: " + MyStack.size()); 
    System.out.println("Capacity of MyStack: " + MyStack.capacity()); 
  }
}

The output of the above code will be:

Size of MyStack: 5
Capacity of MyStack: 10

❮ Java.util - Stack