Stack capacity() method in Java with Example
Last Updated :
24 Dec, 2018
Improve
The capacity() method of Stack Class is used to get the capacity of this Stack. That is the number of elements present in this stack container.
Syntax:
Java
Java
public int capacity()Parameters: This function accepts a parameter E obj which is the object to be added at the end of the Stack. Return Value: The method returns integer value which is the capacity of the Stack Below program illustrate the Java.util.Stack.capacity() method: Example 1:
// Java code to illustrate boolean capacity()
import java.util.*;
import java.util.ArrayList;
public class GFG {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use add() method to add elements in the Stack
stack.add("Geeks");
stack.add("for");
stack.add("Geeks");
stack.add("10");
stack.add("20");
// Displaying the Stack
System.out.println("The Stack is: " + stack);
// checking capacity
System.out.println("Capacity: "
+ stack.capacity());
}
}
// Java code to illustrate boolean capacity()
import java.util.*;
import java.util.ArrayList;
public class GFG {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use add() method to add elements in the Stack
stack.add("Geeks");
stack.add("for");
stack.add("Geeks");
stack.add("10");
stack.add("20");
// Displaying the Stack
System.out.println("The Stack is: " + stack);
// checking capacity
System.out.println("Capacity: "
+ stack.capacity());
}
}
Output:
Example 2:
The Stack is: [Geeks, for, Geeks, 10, 20] Capacity: 10
// Java code to illustrate
// boolean add(Object element)
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack
= new Stack<Integer>();
// Use add() method
// to add elements in the Stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
stack.add(50);
// Displaying the Stack
System.out.println("The Stack is: " + stack);
// checking capacity
System.out.println("Capacity: "
+ stack.capacity());
}
}
// Java code to illustrate
// boolean add(Object element)
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack
= new Stack<Integer>();
// Use add() method
// to add elements in the Stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
stack.add(50);
// Displaying the Stack
System.out.println("The Stack is: " + stack);
// checking capacity
System.out.println("Capacity: "
+ stack.capacity());
}
}
Output:
The Stack is: [10, 20, 30, 40, 50] Capacity: 10