Call by value and Call by reference Java Tutorial

Call by value and Call by reference Java Tutorial

Does Call by reference Java supports?

This is a very basic question asked in every interview and should known to each programmer also.

Everyone says "no" as Java does not support pointers. No one actually see the address of the object in Java. No one can dream of call by reference without pointers with their experience of C/C++.

Of course, they are very correct.

In Java the method parameters can be primitive data types or object references. Both are passed as value only but small tricky explanation is here for object references. I repeat, when primitive data types are passed as method parameters, they are passed by value (a copy of the value) but incase of object references, the reference is copied (of course, here also a copy only) and passed to the called method. That is, object reference is passed as a value. So, original reference and the parameter copy both will refer the same Java object. As both refer the same object, if the calling method changes the value of its reference (passed from calling method), the original object value itself changes. Note that object itself is not passed, but it’s references is passed.

Object reference is a handle to a Java object. Do not compare this reference term with the used in C/C++. In C/C++, the reference directly points to the memory address of a variable and can be used for pointer manipulations.

Finally to say, in Java, everyone is passed by value. But with objecct, the value of the reference is passed.

Let us see two programs on call by value and call by reference.

Case 1: Call-by-value or Pass-by-value

In the following program, a data type int is passed as parameter to a method call.

The variable x value 10 is passed to parameter of y of display() method. As copy of x is passed, changing y does not change x value in main() method.

Case 2: Call by reference Java or Pass-by-reference

Here, for display() method the reference of StringBuffer object is passed.

The value of object reference sb1 is passed to sb2. sb1 literal value "Hello" is passed to sb2. Now sb1 reference and sb2 reference refer the same object. Changing sb2 affects sb1 also. Both sb1 and sb2 prints "HelloWorld".

View All for Java Differences on 90 Topics

2 thoughts on “Call by value and Call by reference Java Tutorial

Leave a Reply

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