Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is stack.push() in Java?

Harris Amjad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring