3.4 Pass by value and pass by reference

The concept

Today, we are going to learn a very important concept of programming. Pass by value and pass by reference. In Apex, all the primitive type variables are pass by value and all the object type variables are pass by reference.

So, what does that mean? It means, when a parameter is passed into a function, if the parameter is of primitive type, Apex will make a copy of that variable can use that copy in the function. However, if the parameter is of an object type, Apex will directly use that object in the function.

Let’s see some code first. Create a Util class and type in the following code. This code assumes you already have last post‘s Commodity class.


public class Util 
{
    public void changeNumber(Decimal d)
    {
        d += 10;
    }
    
    public void changeString(String s) 
    {
    	s = s + 'Hello';    
    }
    
    public void changeObject(Commodity c)
    {
        c.price += 20;
    }
}

Then go into your anonymous block. Type in the following code and execute:

Decimal d = 10;
String s = 'Lance ';
Commodity c = new Commodity();
c.price = 90;

Util u = new Util();
u.changeNumber(d);
u.changeString(s);
u.changeObject(c);

System.debug(d);
System.debug(s);
System.debug(c.price);

Your result should be similar to following screenshot:

passbyvalue

 

A bit explanation

As we have explained before the code. For all primitive type variables, including numbers, string and boolean, Apex functions will pass by the value. It means it will make a hard copy of the original variable and use that hard copy of it throughout the function body. So if you change the variable value in the function, the original variable won’t be changed.

However, if you pass an Object type variable into Apex function, it will pass the reference, which is a totally different story. Apex will directly use that variable in the function body and all the changes will be kept.

Exercise

Try to play with both primitive type and object type variables and see whether they keep the changed value. Do some experiments by yourself!

Next Post

3.5 Public and private modifiers

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *