0

I have a very small program:

    public static void main(String[] args) {

Queue<String> queue = new LinkedList<String>();
queue.add("one");
queue.add("two");
queue.add("tree");

printQueue(queue);
customizeQueue(queue);
printQueue(queue);
}

private static void customizeQueue(Queue<String> queue) {
queue.add("four");
queue.add("five");
printQueue(queue);
}

private static void printQueue(Queue<String> queue) {
for(String s: queue){
    System.out.print(s + " ");
}
System.out.println();
}

I'm expecting an output of:

one two tree
one two tree four five
one two tree

However I'm getting:

one two tree
one two tree four five
one two tree four five

I'm not sure why this is happening. Am I passing the reference of the LinkedList instance? Can somebody please clarify why I'm not getting my expected output.

3 Answers3

4

All types are passed by value in Java. However, what you are passing is not the object, but the reference to the object. This means that a copy of your whole queue is not created when you pass the reference, instead only a copy of the reference is created. The newly created reference still belongs to the same object and therefore when you do a queue.add() , elements are added to the real object. On the other hand, reassigning the reference in the function queue = new LinkedLIst<String>()would have had no effect on the reference in the calling function.

AnkurVj
  • 7,958
  • 10
  • 43
  • 55
1

Objects are passed by reference in Java. Only primitives types are passed by value.

Snicolas
  • 37,840
  • 15
  • 114
  • 173
0

You're not passing a copy of the queue, you're passing the queue iteself. So when it's modified, the changes aren't limited to the customize call, but affect everything.

zigdon
  • 14,573
  • 6
  • 35
  • 54