Skip to content
Related Articles

Related Articles

Improve Article

Stack push() Method in Java

  • Difficulty Level : Basic
  • Last Updated : 02 Aug, 2018

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);
    }
}
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 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);
    }
}
Output:
Initial Stack: [10, 15, 30, 20, 5]
Final Stack: [10, 15, 30, 20, 5, 1254, 4521]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :