0

QUESTION How come this code here: Object y=x.remove(); removes the object from the queue? Isn't this just a variable assignment. Why does it run the code, when we are not calling it? Does variable deceleration call the methods as well?

Queue<Integer> x = new LinkedList<Integer>();
    x.add(5);
    x.add(7)
    Object y=x.remove(); //<------THIS
    x.add(4)
    System.out.println(x.element());
Avinash Kumar
  • 288
  • 6
  • 21

3 Answers3

2

On the right hand side of the = you have an expression. That expression is evaluated and the result is assigned to the variable on the left hand side.

In your case that expression consists of a method invocation. That call to remove() returns the removed object. Which then gets assigned to y. And to be precise: the method removes the first element you added to the queue.

That is all there is to this.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

Well from the documentation of the method itself its very clear what it does there:

/**
 * Retrieves and removes the head of this queue.  This method differs
 * from {@link #poll poll} only in that it throws an exception if this
 * queue is empty.
 *
 * @return the head of this queue
 * @throws NoSuchElementException if this queue is empty
 */
E remove();

Dry run your code to find the details:

x.add(5): --> 5
x.add(7); --> 5,7
Object y=x.remove(); --> 7, y=5
x.add(4); --> 7,4
System.out.println(x.element()); --> Prints 7 (head without removing this time)
Naman
  • 27,789
  • 26
  • 218
  • 353
0

You are calling method of a queue class(.remove()). And this method remove the first element of the queue and return it. You can use peek method ( Object y=x.peek(); ), if you want to check the first element of the queue without removing it.

Oguz
  • 1,867
  • 1
  • 17
  • 24