#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    5
    Rep Power
    0

    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.

    Code:
    [1] Shirt myShirt = new Shirt();
    [2] Shirt yourShirt = new Shirt();
    
    [3] myShirt = yourShirt;
    
    [4] myShirt.colorCode = 'R';
    [5] yourShirt.colorCode = 'G';
    
    [6] System.out.println("Shirt color: " + myShirt.colorCode);
    The above code outputs: Shirt color: G

    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.

    Code:
    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);
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2010
    Posts
    73
    Rep Power
    15
    Hi,

    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.

    Tutorial

    Hope this helps
    slink
    Last edited by slink; November 7th, 2012 at 02:42 AM.

IMN logo majestic logo threadwatch logo seochat tools logo