Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java, C#, and JavaScript Call by Value and Reference

DZone's Guide to

Java, C#, and JavaScript Call by Value and Reference

Need a quick guide for doing so? Check out Mohsen Salehi's article about it.

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

We 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)    

image00

Java (Part I)

image02JavaScript (Part I)

image10

image03

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)

image08

Java (Part II)

image05

JavaScript (Part II)

image04

image07

Now we change the code and create new instance in sum method of input object:

C# (Part III)

image06

Java (Part III)


image09

Now I change call by value to reference:

C# (Part IV)

image01

Java (Part IV)

image11

So we have an error here. You simply can’t do that in Java, since Java doesn’t support pointers …

But in JavaScript:

  1. JavaScript is always pass by value, but when a variable refers to an object (including arrays), the “value” is a reference to the object.
  2. Changing the value of a variable never changes the underlying primitive or object, it just points the variable to a new primitive or object.
  3. However, changing a property of an object referenced by a variable does change the underlying object.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
java ,c# ,java script

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}