Write a Java program to Print the all Positive numbers in the queue


The Java code defines a class PrintPositiveNumbers with a method printPositiveNumbers that prints all positive numbers present in a given Queue of integers.

  • The printPositiveNumbers method takes a Queue<Integer> named queue as input and prints all positive 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 greater than 0 (i.e., positive). If num is positive, it prints the number followed by a space using System.out.print().
  • After the loop finishes, all positive 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 printPositiveNumbers method is then called with the queue as an argument, and all positive numbers present in the queue are printed using System.out.print().

Source Code

import java.util.*;
 
public class PrintPositiveNumbers
{
	public static void printPositiveNumbers(Queue<Integer> queue)
	{
		System.out.print("Positive Numbers in the Queue : ");
		for (int num : queue)
		{
			if (num > 0)
			{
				System.out.print(num + " ");
			}
		}
		System.out.println();
	}
 
	public static void main(String[] args)
	{
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(10);
		queue.offer(-20);
		queue.offer(30);
		queue.offer(-40);
		queue.offer(50);
		queue.offer(-60);
		queue.offer(-70);
		queue.offer(80);
		queue.offer(90);
		queue.offer(-100);
		System.out.println("Original Queue : "+queue);
 
		printPositiveNumbers(queue);
	}
}
 

Output

Original Queue : [10, -20, 30, -40, 50, -60, -70, 80, 90, -100]
Positive Numbers in the Queue : 10 30 50 80 90

Example Programs