Call by value and Call by reference in Java

Call by value and Call by reference in Java

 

In java programming language there is only call by value concept. Call by reference is not supported by java. Calling a method by passing the value is known as call by value.

 

Example of call by value in Java:

When we call a method by value the original value is not affected. Consider the following example:

CODE:

class ABC {

int id = 122;

void alter (int id) {

id = id + 2;

}

public static void int main (String args []) {

ABC a1 = new ABC ();

system. out. println (“Value before altering” + a1. id);

a1. alter (24);

system. out. println (“Value after altering” + a1. id);

}

}

OUTPUT:

Value before altering 122

Value after altering 122

In the above example it can be seen that there is no affect on the value of the data member but the value will be changed of only the local variable.

 

Another example of call by value in Java:

Consider the following example to call a method by value in java:

CODE:

class ABC {

int id = 122;

void alter (ABC a1) {

a1. id = a1. id + 2;

}

public static void int main (String args []) {

ABC a1 = new ABC ();

system. out. println (“Value before altering” + a1. id);

a1. alter (a1);

system. out. println (“Value after altering” + a1. id);

}

}

OUTPUT:

Value before altering 122

Value after altering 124

In the above example we passed the reference variable of the class to the method or the object of the class to the method and it can be seen that the value of the data member “id” is changed.