Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

stack
addelement
java
communitycreator

What is the Stack.addElement() method in Java?

Programming Bytes

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 addElement() method of the Stack class can be used to add an element at the end of a Stack object.

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

Syntax

public void addElement(E obj)

Argument

The element to be added to the Stack object is passed as an argument.

This method doesn’t return any value.

Code

The code below shows how we can use the addElement() class to add elements in a Stack object.

import java.util.Stack;
class Add {
public static void main( String args[] ) {
// Creating Stack
Stack<Integer> stack = new Stack<>();
// Adding elements
stack.addElement(1);
stack.addElement(2);
stack.addElement(3);
stack.addElement(4);
// Printing Stack
System.out.println("The Stack is: " + stack);
// Adding new elements to the end
stack.addElement(5);
// Printing the new Stack
System.out.println("The Stack is: " + stack);
}
}

Explanation

In the code above:

  • We created a new object for the Stack class with the name stack in line 5.

  • After that, we added the elements 1,2,3,4 to stack using the addElement() method in lines 8-11. The elements are added to the end of stack.

  • Then in line 17, we used the addElement() method to add the element 5 to the end of stack.

RELATED TAGS

stack
addelement
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