+ 2
Can anyone tell me,if this code is an example of Call by reference?
10 Respuestas
+ 3
Ervis Meta don't mix C/C++ with java. Syntax is bit different
+ 2
Denise Roßberg it is showing error
+ 2
Denise Roßberg means reference brings changes but not the value?
+ 2
Tapabrata Banerjee only we have to take a reference instead of variable right?
+ 2
Denise Roßberg the thing which I mentioned to you earlier was correct or not?
+ 1
Atul
Let me try to explain:
You have this array in your main method. And you have an array in the fun() method.
fun() don't get a copy of this array, it get's a reference. What looks like two arrays are actually just one.
That's why arr outside fun() is changed.
It is the same with
int[] arr = new int[2];
int[] secondArr = arr;
Two objects but with same rerence. Java has no pointers but I think reference is similiar to pointers. Both objects points to the same memory location.
+ 1
Atul
You could get a value if you write a method which returns a value. That has nothing to do with reference.
The point is: When you work with objects/reference you need to think about which changes are wanted and which not.
For example a sorting method can work with reference. You want to sort your list/array, changes are wanted.
But sometimes it is better to work with a copy because you need your original object.
0
This program is not an example of the reference beause it does not include any pointers to point to addresses of variables.
The swap function just get two values and print them swapped.If those values were stored at variables, they won't change at all.
The solution is the using of pointers to realise the 'call by reference':
class Swap{
static void Swap(int* a, int* b){
int* t=a;
a=b;
b=t;
System.out.println(a+" "+b);
}
}
public class Program
{
public static void main(String[] args) {
Swap sc=new Swap() ;
int a = 40;
int b = 50;
int* ptr1 = &a;
int* ptr2 = &b;
sc.Swap(ptr1,ptr2);
}
}
0
Atul
To keep it simple:
a method which takes primitive variables -> by value
a method which takes objects -> by reference
You can try to write a method which takes an array. Do some changes on the array.
public static void fun(int[] arr){
arr[0] = 7;
}
int[] arr = {1,2,3};
fun(arr)
Now see what happend to arr. And compare this with a method which do something with an int or other primitive.