Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Stack.lastElement 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 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 lastElement() method of the Stack class returns the last element present in the Stack object.

Syntax

public E lastElement();

This method doesn’t take any arguments.

Return value

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

Code

import java.util.Stack;
class StackLastElementExample {
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 last element
System.out.println("The last element of the stack is : " + stack.lastElement());
}
}

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 lastElement method on the stack object to get the last element.

stack.lastElement();

The code will return 3.

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