What is stack.push() in Java?

The stack.push() function in Java is used to insert an element at the top of the stack.

The following illustration shows a visual representation of the stack.push() function.

Visual representation of stack.push() function

The java.util.* module is required in order to use stack.push().

Syntax

stack_name.push(element)
//where stack_name is name of the stack

Parameters

This function requires an element as a parameter.

Return value

The stack.push() function inserts an element sent as a parameter at the top of the stack.

Code

import java.util.*;
class JAVA {
public static void main( String args[] ) {
Stack<Integer> Stack = new Stack<Integer>();
Stack.add(2);
Stack.add(5);
Stack.add(3);
Stack.add(1);
//Stack before adding 0 = 2->5->3->1
System.out.println("Following are the elements in Stack before 0: " + Stack);
Stack.push(0);
//Stack after adding 0 = 2->5->3->1->0
System.out.println("Following are the elements in Stack after 0: " + Stack);
}
}

Free Resources