Example is a Card class with a swap() method. Two Card objects are instantiated. The method swaps them by declaring a third Card variable, but without instantiating a third object. The third variable is used as the temp holder to support a swap. I expected the swap not to work, because the temp variable refers to the first object, then the first object is assigned the second object, and the second object is assigned temp, which picks up the change to the first object, according to my assumptions.
public class Tester
{
public static void main(String[] args)
{
Card[] cards = new Card[2];
cards[0] = new Card('x');
cards[1] = new Card('y');
System.out.println( cards[0].getVal() + "\n" + cards[1].getVal() + "\n" );
Card.swap(cards);
System.out.println( cards[0].getVal() + "\n" + cards[1].getVal() + "\n" );
}
}
//Card class --------------------------------------------------------------------
class Card
{
private char value;
public Card(char value)
{
set(value);
}
public static void swap(Card[] cards){
Card temp = cards[0];
cards[0] = cards[1];
cards[1] = temp;
}
public boolean set(char value)
{
this.value = value;
return true;
}
public char getVal()
{
return value;
}
}
Output:
x
y
y
x
I expect cards[0] and cards[1] to refer to the memory that was referred to by cards[1] before temp is assigned to cards[1]. I expect the dereference of cards[0] to be lost.
The actual result is that cards[0] is swapped with cards[1]. (Is this a true copy, or a reference switch?) My understanding was that, since all Java variables are references, temp's dereference would become cards[1] when cards[0]'s dereference became cards[1]. Now it looks like temp has its own memory, even though it was not assigned a heap object in a "new" operation. I read elsewhere something that suggested to me that this is how method variables work, but I couldn't find anything that confirmed that it is how method variables of a user-defined type, or any non-primitive type, work.