What is the Stack.addElement() method in Java?
The addElement() method of the Stack class can be used to add an element at the end of a Stack object.
The
Stackclass is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
Syntax
public void addElement(E obj)
Argument
The element to be added to the Stack object is passed as an argument.
This method doesn’t return any value.
Code
The code below shows how we can use the addElement() class to add elements in a Stack object.
import java.util.Stack;class Add {public static void main( String args[] ) {// Creating StackStack<Integer> stack = new Stack<>();// Adding elementsstack.addElement(1);stack.addElement(2);stack.addElement(3);stack.addElement(4);// Printing StackSystem.out.println("The Stack is: " + stack);// Adding new elements to the endstack.addElement(5);// Printing the new StackSystem.out.println("The Stack is: " + stack);}}
Explanation
In the code above:
-
We created a new object for the
Stackclass with the namestackin line 5. -
After that, we added the elements
1,2,3,4tostackusing theaddElement()method in lines 8-11. The elements are added to the end ofstack. -
Then in line 17, we used the
addElement()method to add the element5to the end ofstack.