Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Stack.firstElement 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.

Overview

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.

The firstElement() method of the Stack class returns the first element present in the Stack object.

Syntax

public E firstElement();
Defining the function

Parameters

This method doesn’t take any parameters.

Return value

The firstElement() method returns the first element of the Stack object. If the Stack object is empty, then NoSuchElementException is thrown.

Code

import java.util.Stack;
class FirstElementExample {
public static void main( String args[] ) {
// Creating Stack
Stack<Integer> stack = new Stack<>();
// add elememts
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("The stack is: " + stack);
// Print first element
System.out.println("The first element of the stack is : " + stack.firstElement());
}
}
Try it out yourself

Explanation

In the code above, we create a Stack object and use the push method to add three elements, 1, 2, and 3. We then call the firstElement method on the stack object to get the first element.

stack.firstElement();
Getting the first element from the stack

The code above will return 1.

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