Does Java support call by reference?

Author - Webner

Java does not support call by reference because in call by reference we need to pass the address and address are stored in pointers. Java does not support pointers and it is because pointers break the security. Java does manipulate objects by reference and all object variables are references. Pass by reference in Java means passing the address itself as a copy. In Java the arguments are always passed by value. Java only supports pass by value.

Example of Call by value in java : In case of call by value original value is not changed. Let’s take a simple example:

class Operation {
int data = 50;
void change(int data) {
data = data + 100; //changes will be in the local variable only  
    }
public static void main(String args[]) {
Operation obj = new Operation();
System.out.println("before change " + obj.data);
obj.change(500);
System.out.println("after change " + obj.data);
    }
}

Output:

Before change 50
After change 50

Another Example of the call by Value in java:

In case of call by reference original value is changed if we make changes in the called method. If we pass object in place of any primitive value and change attribute values of the object, original value will be changed. Let’s take an example:

class Operation2 {
int data = 50;
public static void main(String args[]) {
Operation2 obj = new Operation2();
System.out.println("Before change " + obj.data);
obj.change(obj); //passing object as an argument
System.out.println("After change " + obj.data);
}
void change(Operation2 obj) {
obj.data = obj.data + 100; //changes will be in the instance variable  
    }
}

Output:

Before change 50
After change 150

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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