Java Stack - add() Method
The java.util.Stack.add() method is used to add a new element at the top of the stack.
Syntax
public boolean add(E element)
Here, E is the type of element maintained by the container.
Parameters
element |
Specify element which need to be added in the stack. |
Return Value
Returns true if the element is successfully added, else returns false.
Exception
NA
Example:
In the example below, the java.util.Stack.add() method is used to add new element at the top 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); //adding element using add() method MyStack.add(100); MyStack.add(200); //printing stack System.out.println("MyStack contains: " + MyStack); } }
The output of the above code will be:
MyStack contains: [10, 20, 30, 100, 200]
❮ Java.util - Stack