November 7th, 2012, 01:24 AM
New to Java and and trying to understand this code
Here is the example that I can't figure out why it outputs what it does. I have added line numbers to help reference my question.
The above code outputs: Shirt color: G
 Shirt myShirt = new Shirt();
 Shirt yourShirt = new Shirt();
 myShirt = yourShirt;
 myShirt.colorCode = 'R';
 yourShirt.colorCode = 'G';
 System.out.println("Shirt color: " + myShirt.colorCode);
I thought all programming languages interpreted code line by line?
When the code reaches line 3, myShirt is assigned the properties of yourShirt. At this point there is no colorCode property to pass on.
At line 4, myShirt is now assigned 'R' as the property.
Should not the code order be as below in order to output the value of 'G' for myShirt color?
Shirt myShirt = new Shirt();
Shirt yourShirt = new Shirt();
myShirt.colorCode = 'R';
yourShirt.colorCode = 'G';
myShirt = yourShirt;
System.out.println("Shirt color: " + myShirt.colorCode);
November 7th, 2012, 02:22 AM
This can be a tricky concept to understand when beginning Java.
Line 1 creates a new Shirt in memory and assigns myShirt as a reference to it.
Line 2 creates another Shirt in a different area of memory and assigns yourShirt as a reference to that.
Line 3 does not actually copy the properties. Instead, the myShirt reference is changed to point at the area in memory that yourShirt is pointing to. So now both myShirt and yourShirt references are pointing to the same thing.
Line 4 changes the color of the referenced Shirt.
Line 5 again changes the color of the same referenced Shirt.
Line 6 prints the color of the shirt through the myShirt reference. You would get the same result if you printed the color of yourShirt, as both references are pointing at the same thing.
Hope this helps
Last edited by slink; November 7th, 2012 at 02:42 AM.