Java, C#, and JavaScript Call by Value and Reference
Need a quick guide for doing so? Check out Mohsen Salehi's article about it.
Join the DZone community and get the full member experience.
Join For FreeWe have two simple methods — one method in Java one method in C#. Both of these two methods get one parameter and return parameter+1 after it. I changed this sample for testing an object input not primitive value.
C# (Part I)
Java (Part I)
JavaScript (Part I)
Also, you can see our parameter does not change after call function sum.
We change param type from integer to a class with a one property as integer.
C# (Part II)
Java (Part II)
JavaScript (Part II)
Now we change the code and create new instance in sum method of input object:
C# (Part III)
Java (Part III)
Now I change call by value to reference:
C# (Part IV)
Java (Part IV)
So we have an error here. You simply can’t do that in Java, since Java doesn’t support pointers …
But in JavaScript:
- JavaScript is always pass by value, but when a variable refers to an object (including arrays), the “value” is a reference to the object.
- Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
- However, changing a property of an object referenced by a variable does change the underlying object.
Opinions expressed by DZone contributors are their own.
Comments