Which operation is used to add an element to a Stack?

Java MCQ: Which operation is used to add an element to a Stack?

A) Enqueue
B) Dequeue
C) Push
D) Pop

Answer:

C) Push

Explanation:

The operation used to add an element to a stack is known as “push.” The push operation places an element on the top of the stack, adhering to the Last-In-First-Out (LIFO) principle. The new element becomes the most recently added element and will be the first one removed when a pop operation is performed.

The push operation is fundamental to the functioning of a stack and is usually performed in constant time, O(1). This efficiency makes stacks a suitable data structure for scenarios requiring frequent additions and removals of elements. For example, in function call management within a program, each function call is “pushed” onto the call stack, and upon completion, it is “popped” off the stack.

Here’s an example of a push operation in Java using the Stack class:


import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        System.out.println(stack); // Outputs: [10, 20, 30]
    }
}

In this example, the numbers 10, 20, and 30 are pushed onto the stack in that order. The stack will now contain these elements, with 30 at the top. Understanding the push operation is crucial for working with stacks, as it directly affects how data is stored and accessed in this data structure.

Reference links:

https://www.javaguides.net/p/java-stack-tutorial.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top