What is the Stack.push method in Java?
The push method of the Stack class can be used to add an element to the top of the Stack.
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 E push(E item)
Return value
This method returns the inserted element.
import java.util.Stack;class StackPushExample {public static void main( String args[] ) {// Creating StackStack<Integer> stack = new Stack<>();// add elememtsstack.push(1);System.out.println("The Stack is: " + stack);// add elememtsstack.push(2);stack.push(3);System.out.println("The Stack is: " + stack);}}
In the above code, we create a Stack object and use the push method to add the elements to the top of the stack.