Java Intermediate

0% completed

Previous
Next
Quiz
Question 1
What is the difference between the peek() and element() methods in a queue?
A
peek() returns null if the queue is empty, while element() throws an exception.
B
peek() removes the head element, while element() does not.
C
element() returns null if the queue is empty, while peek() throws an exception.
D
Both methods behave identically.
Question 2
Examine the following code snippet using PriorityQueue:
import java.util.PriorityQueue;

public class Test {
    public static void main(String[] args) {
        PriorityQueue<Integer> numbers = new PriorityQueue<>();
        numbers.add(20);
        numbers.add(5);
        numbers.add(15);
        numbers.add(10);
        System.out.println("PriorityQueue: " + numbers);
        Integer head = numbers.poll();
        System.out.println("Polled Element: " + head);
    }
}
What will the PriorityQueue output and which element is polled?
A
PriorityQueue: [20, 5, 15, 10]; Polled Element: 20
B
PriorityQueue: [10, 15, 20, 5]; Polled Element: 10
C
PriorityQueue: [15, 10, 5, 20]; Polled Element: 15
D
PriorityQueue: [5, 10, 15, 20]; Polled Element: 5
Question 3
Consider the following code snippet using ArrayDeque as a stack:
import java.util.ArrayDeque;

public class Test {
    public static void main(String[] args) {
        ArrayDeque<String> stack = new ArrayDeque<>();
        stack.addFirst("Plate 1");
        stack.addFirst("Plate 2");
        stack.addFirst("Plate 3");
        System.out.println("Stack: " + stack);
        String top = stack.removeFirst();
        System.out.println("Popped: " + top);
        System.out.println("Stack after pop: " + stack);
    }
}
What behavior is demonstrated by this code?
A
FIFO behavior (queue).
B
LIFO behavior (stack).
C
Random removal of elements.
D
Sorted order of elements.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next