Open In App

Stack push() Method in Java

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Code to illustrate push() Method
 
import java.util.*;
 
// Main class
public class StackDemo {
 
    // Main driver method
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack& lt;
        String& gt;
        STACK = new Stack& lt;
        String& gt;
        ();
 
        // Adding elements into the stack
        // using push() method
        STACK.push(" Welcome & quot;);
        STACK.push(" To & quot;);
        STACK.push(" Geeks & quot;);
        STACK.push(" For & quot;);
        STACK.push(" Geeks & quot;);
 
        // Displaying the Stack
        System.out.println(" Initial Stack
                           : "
                           + STACK);
 
        // Pushing elements into the stack
        STACK.push(" Hello & quot;);
        STACK.push(" World & quot;);
 
        // Displaying the final Stack
        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




// 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);
        STACK.push(null);
 
        // 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);
    }
}


Output:

Initial Stack: [10, 15, 30, 20, 5]
Final Stack: [10, 15, 30, 20, 5, 1254, 4521]


Last Updated : 10 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads