
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Returning Even Numbers from a Stack in Java
Stacks in Java
A stack is a Last-In-First-Out (LIFO) data structure. As shown below, the last book inserted onto the stack is the first to be removed, and the first book inserted into the stack is the last to be removed.
In Java, a stack of integers can be created by importing the java.util.Stack package and invoking the Stack() constructor. Integer objects can be pushed onto the stack using the push() method. An example is provided in the following code snippet.
Example
Following is an example program ?
import java.util.Stack; public class Testing { public static void main(String[] args) { Stack<Integer> numbers = new Stack<Integer>(); numbers.push(12); numbers.push(1); numbers.push(3); numbers.push(15); numbers.push(4); System.out.println(numbers); } }
Following is the output of the above program ?
[12, 1, 3, 15, 4]
Returning Even Numbers from the Stack
The get() and pop() methods can be used to access the elements of a stack in Java. The peek() method can access the object at the top of the stack without removing it. We can use the pop() method to access the integers in the stack as it is more in line with how a stack functions i.e. as a LIFO data structure.

Example
Following is an example program which retrieves even numbers fro a stack. In here,
- The empty() method is used in a while loop to test if the stack is empty
- If the stack is not empty, the number is popped from the top of the stack and stored as an integer
- The modulo operator is used to check if the number is even
- If the number is even, it is output to the screen
import java.util.Stack; public class Example { public static void main(String[] args) { Stack<Integer> numbers = new Stack<Integer>(); numbers.push(12); numbers.push(1); numbers.push(3); numbers.push(15); numbers.push(4); System.out.println("Contents of the Stack: " + numbers); System.out.println("Even Numbers in the Stack: "); while(!(numbers.empty())) { int number = numbers.pop(); if(number%2 == 0){ System.out.println(number); } } } }
Following is the output of the above program ?
Contents of the Stack: [12, 1, 3, 15, 4] Even Numbers in the Stack: 4 12