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 Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

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 Stack
Stack<Integer> stack = new Stack<>();
// Adding elements
stack.addElement(1);
stack.addElement(2);
stack.addElement(3);
stack.addElement(4);
// Printing Stack
System.out.println("The Stack is: " + stack);
// Adding new elements to the end
stack.addElement(5);
// Printing the new Stack
System.out.println("The Stack is: " + stack);
}
}

Explanation

In the code above:

  • We created a new object for the Stack class with the name stack in line 5.

  • After that, we added the elements 1,2,3,4 to stack using the addElement() method in lines 8-11. The elements are added to the end of stack.

  • Then in line 17, we used the addElement() method to add the element 5 to the end of stack.

Free Resources