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. It also accepts the null value unlike ArrayDeque.push() which throws java.lang.NullPointerException on doing the same.
Below programs illustrate the Java.util.Stack.push() method:
Program 1: Adding String elements into the Stack.
Java
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack& lt;
String& gt;
STACK = new Stack& lt;
String& gt;
();
STACK.push(" Welcome & quot;);
STACK.push(" To & quot;);
STACK.push(" Geeks & quot;);
STACK.push(" For & quot;);
STACK.push(" Geeks & quot;);
System.out.println(" Initial Stack
: "
+ STACK);
STACK.push(" Hello & quot;);
STACK.push(" World & quot;);
System.out.println(" Final Stack
: "
+ STACK);
}
}
|
Output:
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
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<Integer> STACK = new Stack<Integer>();
STACK.push( 10 );
STACK.push( 15 );
STACK.push( 30 );
STACK.push( 20 );
STACK.push( 5 );
STACK.push( null );
System.out.println("Initial Stack: " + STACK);
STACK.push( 1254 );
STACK.push( 4521 );
System.out.println("Final Stack: " + STACK);
}
}
|
Output:
Initial Stack: [10, 15, 30, 20, 5]
Final Stack: [10, 15, 30, 20, 5, 1254, 4521]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Jun, 2022
Like Article
Save Article