0% found this document useful (0 votes)
11 views3 pages

Java Stack Methods With Examples and List

The document outlines the methods of the Java Stack class, including push, pop, peek, isEmpty, search, and size. Each method is explained with its syntax and examples demonstrating its usage. This serves as a quick reference for understanding how to manipulate a stack in Java.

Uploaded by

relishmunjal07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views3 pages

Java Stack Methods With Examples and List

The document outlines the methods of the Java Stack class, including push, pop, peek, isEmpty, search, and size. Each method is explained with its syntax and examples demonstrating its usage. This serves as a quick reference for understanding how to manipulate a stack in Java.

Uploaded by

relishmunjal07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Java Stack Class - Methods with Examples

List of Methods in the Java Stack Class:

1. push(E item)

2. pop()

3. peek()

4. isEmpty()

5. search(Object o)

6. size()

Explanation of Methods with Examples:

1. push(E item):

- Pushes an item onto the top of the stack.

- Syntax: stack.push(item);

Example:

Stack<Integer> stack = new Stack<>();

stack.push(10);

stack.push(20);

stack.push(30);

2. pop():

- Removes and returns the top item of the stack.


- Syntax: E item = stack.pop();

Example:

Integer poppedItem = stack.pop(); // pops 30

3. peek():

- Returns the top item of the stack without removing it.

- Syntax: E item = stack.peek();

Example:

Integer topItem = stack.peek(); // returns 20 but does not remove it

4. isEmpty():

- Checks if the stack is empty.

- Syntax: boolean isEmpty = stack.isEmpty();

Example:

boolean emptyStatus = stack.isEmpty(); // returns false if there are elements in the stack

5. search(Object o):

- Returns the 1-based position of the element from the top of the stack.

- Returns -1 if the item is not found.

- Syntax: int position = stack.search(o);

Example:

int position = stack.search(10); // returns 1 if 10 is at the top


6. size():

- Returns the number of elements in the stack.

- Syntax: int size = stack.size();

Example:

int stackSize = stack.size(); // returns the number of elements in the stack

You might also like