Write a Java program to Print the all Even numbers in the queue
The Java code defines a class PrintEvenNumbers with a method printEvenNumbers that prints all even numbers present in a given Queue of integers.
- The printEvenNumbers method takes a Queue<Integer> named queue as input and prints all even numbers present in the queue.
- The method uses a loop to iterate through each element in the queue using an enhanced for loop (also known as a "for-each" loop). In each iteration, the variable num takes the value of the current element from the queue.
- Inside the loop, the code checks if num is even (i.e., its remainder when divided by 2 is 0). If num is even, it prints the number followed by a space using System.out.print().
- After the loop finishes, all even numbers present in the queue will be printed on the same line.
- The method then uses System.out.println() to move to the next line.
- In the main method, a Queue<Integer> named queue is created using the LinkedList implementation of the Queue interface. Integers are added to the queue using the offer() method.
- The original queue is printed using System.out.println().
- The printEvenNumbers method is then called with the queue as an argument, and all even numbers present in the queue are printed using System.out.print().
Source Code
import java.util.*;
public class PrintEvenNumbers
{
public static void printEvenNumbers(Queue<Integer> queue)
{
System.out.print("Even Numbers in the Queue : ");
for (int num : queue)
{
if (num % 2 == 0)
{
System.out.print(num + " ");
}
}
System.out.println();
}
public static void main(String[] args)
{
Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.offer(5);
queue.offer(6);
queue.offer(7);
queue.offer(8);
queue.offer(9);
queue.offer(10);
System.out.println("Original Queue : "+queue);
printEvenNumbers(queue);
}
}
Output
Original Queue : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even Numbers in the Queue : 2 4 6 8 10