RU beehive logo ITEC dept promo banner
ITEC 120
2010fall
ibarland

homeinfolectslabsexamshws
tutor/PIsbreeze (snow day)
Object120 + its docsjava.lang docsjava.util docs

lect13b
passing references by value

Tomorrow, (a) bring a camera to lab, and (b) don't wear green. (I'll try to get a green-screen, and next week you can use that image to superimpose yourself on another image [of the exact same dimensions].)

You can't write a function to swap your own local variables

  void tryAndSwap( int a, int b ) {
    int tmp;
    tmp = a;
    a = b;     // Assigning to a parameter -- bad style!
    b = tmp;   // Assigning to a parameter -- bad style!
    }
What happens when we try this?
int myFavoriteInt = 5;
int yourFavoriteInt = 23;

tryAndSwap( myFavoriteInt, yourFavoriteInt );

myFavoriteInt == 5     // True, or false?
yourFavoriteInt == 5   // True, or false?
If you draw the pictures of what happens, you'll see that tryAndSwap made its own local variables (a and b), they were initialized when the function was called (with 5 and 23), those local variables were shuffled around, but myFavoriteInt was never touched!

...but you can write a function to swap the shapes of two Robots

  // In class Robot:

  public static void swapRobotShape( Robot r1, Robot r2 ) {
    // What to put here?




    }



// From the code pad, say:
//
Robot optimus = new Robot( "X47", "Daisy", false, false );
Robot optimusPrime = new Robot( "X47'", "Mack Truck", false, false );

optimus.toString();
Robot.swapRobotShape(optimus, optimusPrime);
optimus.toString();

We say: “Java always passes arguments by value”: it takes the actual argument's value, and uses (a copy of) that value to initalize the parameter. The thing to realize is that (in java) “references are values”.

Some languages allow something different: they let you “pass arguments by reference”, a special language-feature that would let you write something like swapInts(int,int). However, this has fallen out of favor recently, and is commonly viewed as something which can add obscure bugs without really giving the programmer more power. Just write methods which return a (reference to) the new items, and assign your variables explicitly.

homeinfolectslabsexamshws
tutor/PIsbreeze (snow day)
Object120 + its docsjava.lang docsjava.util docs


©2010, Ian Barland, Radford University
Last modified 2010.Dec.01 (Wed)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme