Stack push() Method in Java
The Java.util.Stack.push(E element) method is used to push an element into the Stack. The element gets pushed onto the top of the Stack.
Syntax:
STACK.push(E element)
Parameters: The method accepts one parameter element of type Stack and refers to the element to be pushed into the stack.
Return Value: The method returns the argument passed.
Below programs illustrate the Java.util.Stack.push() method:
Program 1: Adding String elements into the Stack.
// Java code to illustrate push() method import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<String> STACK = new Stack<String>(); // Use push() to add elements into the Stack STACK.push("Welcome"); STACK.push("To"); STACK.push("Geeks"); STACK.push("For"); STACK.push("Geeks"); // Displaying the Stack System.out.println("Initial Stack: " + STACK); // Pushing elements into the stack STACK.push("Hello"); STACK.push("World"); // Displaying the final Stack System.out.println("Final Stack: " + STACK); } } |
Initial Stack: [Welcome, To, Geeks, For, Geeks] Final Stack: [Welcome, To, Geeks, For, Geeks, Hello, World]
Program 2: Adding Integer elements into the Stack.
// Java code to illustrate push() method import java.util.*; public class StackDemo { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> STACK = new Stack<Integer>(); // Use push() to add elements into the Stack STACK.push(10); STACK.push(15); STACK.push(30); STACK.push(20); STACK.push(5); // Displaying the Stack System.out.println("Initial Stack: " + STACK); // Pushing elements into the Stack STACK.push(1254); STACK.push(4521); // Displaying the final Stack System.out.println("Final Stack: " + STACK); } } |
Initial Stack: [10, 15, 30, 20, 5] Final Stack: [10, 15, 30, 20, 5, 1254, 4521]
Recommended Posts:
- LinkedBlockingDeque push() method in Java
- LinkedList push() Method in Java
- ArrayDeque push() Method in Java
- ConcurrentLinkedDeque push() method in Java with Examples
- Stack set() method in Java with Example
- Stack pop() Method in Java
- Stack get() method in Java with Example
- Stack contains() method in Java with Example
- Stack firstElement() method in Java with Example
- Stack addElement(E) method in Java with Example
- Stack add(Object) method in Java with Example
- Stack add(int, Object) method in Java with Example
- Stack listIterator() method in Java with Example
- Stack listIterator(int) method in Java with Example
- Stack removeAllElements() method in Java with Example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



