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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.