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 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 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 Stack
Stack<Integer> stack = new Stack<>();
// add elememts
stack.push(1);
System.out.println("The Stack is: " + stack);
// add elememts
stack.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.