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


The Java code defines a class PrintNegativeNumbers with a method printNegativeNumbers that prints all negative numbers present in a given Queue of integers.

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

Source Code

import java.util.*;
 
public class PrintNegativeNumbers
{
	public static void printNegativeNumbers(Queue<Integer> queue)
	{
		System.out.print("Negative 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);
 
		printNegativeNumbers(queue);
	}
}
 

Output

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

Example Programs