Multiple choice technology programming languages

What is the output for the below code ? import java.util.LinkedList; import java.util.Queue; public class Test { public static void main(String... args) { Queue q = new LinkedList(); q.add("newyork"); q.add("ca"); q.add("texas"); show(q); } public static void show(Queue q) { q.add(new Integer(11)); while (!q.isEmpty ( ) ) System.out.print(q.poll() + " "); } }

  1. Compile error : Integer can't add

  2. newyork ca texas 11

  3. newyork ca texas

  4. newyork ca

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

To understand the output of the given code, it is important to know the concept of Queue in Java.

A Queue is a data structure that follows the First-In-First-Out (FIFO) principle. In a Queue, elements are added from the rear and removed from the front. The methods used to add elements to the Queue are 'add' and 'offer', whereas 'poll' and 'remove' are the methods used to remove elements from the Queue.

Now let's go through the code and analyze the output.

The code creates a Queue of Strings named 'q' and adds three Strings to it: "newyork", "ca", and "texas". Then the method 'show(q)' is called, and a new Integer object 11 is added to the Queue 'q' inside the 'show' method. Finally, the elements of the Queue are printed using the 'poll' method.

Since the Queue 'q' has been defined as a Queue of Strings, adding an Integer object to the Queue will result in a compile-time error. Therefore, option A is incorrect.

The 'poll' method removes and returns the head of the Queue. So, the output will be the elements of the Queue in the order they were added. Thus, option C is incorrect because it does not include the added Integer object.

Therefore, the correct answer is:

The Answer is: B. newyork ca texas 11