

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add an element to a Stack in Java
An element can be added into the stack by using the java.util.Stack.push() method. This method pushes the required element to the top of the stack. The only parameter required for the Stack.push() method is the element that is to be pushed into the stack.
A program that demonstrates this is given as follows −
Example
import java.util.Stack; public class Demo { public static void main (String args[]) { Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Guava"); stack.push("Pear"); stack.push("Orange"); System.out.println("The stack elements are: " + stack); } }
Output
The stack elements are: [Apple, Mango, Guava, Pear, Orange]
Now let us understand the above program.
The Stack is created. Then Stack.push() method is used to add the elements to the stack. Finally the stack is displayed. A code snippet which demonstrates this is as follows −
Stack stack = new Stack(); stack.push("Apple"); stack.push("Mango"); stack.push("Guava"); stack.push("Pear"); stack.push("Orange"); System.out.println("The stack elements are: " + stack);
- Related Questions & Answers
- Remove an element from a Stack in Java
- Java Program to find if an element is in Stack
- Get an element from a Stack in Java without removing it
- How do you add an element to a list in Java?
- Check if a Stack contains an element in C#
- Add an element to specified index of ArrayList in Java
- How do I add an element to an array list in Java?
- Add a single element to a LinkedList in Java
- How to add an element to a javascript object?
- Add a shadow to an element with Bootstrap 4
- How to add an address element in HTML?
- How to access each stack element of StackWalker in Java 9?
- How to add a unique id for an element in HTML?
- How to add a class name to an element with JavaScript?
- Add a red border to an element in Bootstrap to indicate danger
Advertisements