Friday, March 30, 2012

difference between call-by-value and call-by-reference

  • Call by Reference vs. Call by Value
http://www.youtube.com/watch?v=loDpVao0Jik&feature=related

  • Java Parameter passing: call by reference and value.
http://www.youtube.com/watch?v=6IBlJNdzP9c

  • String in java is a reference data type as are all non-primitive data types
All Strings in java are objects
Strings in java are immutable thus there are many methods to manipulate strings
String contents can't be changed but replaced with methods in java


  • An Immutable Class
http://www.youtube.com/watch?v=FRjlMs5Xa3A
Immutable class can't be changed


  • 6. Confusion over passing by value, and passing by reference

This can be a frustrating problem to diagnose, because when you look at the code, you might be sure that its passing by reference, but find that its actually being passed by value. Java uses both, so you need to understand when you're passing by value, and when you're passing by reference.

When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only. Once the function finishes, and control is returned to the returning function, the "real" variable will be untouched, and no changes will have been saved. If you need to modify a primitive data type, make it a return value for a function, or wrap it inside an object.

When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference. Yes - a String is actually an object, not a primitive data type.  So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent - which can be either good or bad, depending on whether this was what you intended.

On a side note, since String contains no methods to modify its contents, you might as well be passing by value.

http://www.javacoffeebreak.com/articles/toptenerrors.html

No comments:

Post a Comment