Java - Data Structures - The Stack Class - Java

Stack is a subclass of Vector that implements a standard last-in, first-out stack.

Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

Apart from the methods inherited from its parent class Vector, Stack defines the following methods −


Method & Description


boolean empty()

Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.


Object peek( )

Returns the element on the top of the stack, but does not remove it.


Object pop( )

Returns the element on the top of the stack, removing it in the process.


Object push(Object element)

Pushes the element onto the stack. Element is also returned.


int search(Object element)

Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, .1 is returned.


The following program illustrates several of the methods supported by this collection −

This will produce the following result −


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Java Topics