Call by reference or Call by value in JAVA | Techbirds
Hi all,
This has always been a topic of discussion whether Java passes its parameter through call by reference or call by value. In 1 Line Call by Value.
This question aroused from c/c++ parameter passing methodologies i.e. if in a function we pass a value then it is pass by value.
for ex.
public void passingValue(int x, int y); //calling method int a=3, b=4; passingValue(a,b);
public void passingValue(int x, int y); //calling method int a=3, b=4; passingValue(a,b); |
The above method signature gets the value of x and y (that means the actual values from calling function will be copied to x and y) and then further processing begins, whatever this method does only local value in this x, y are affected.
For call by reference
public void passingRef(int *x, int *y); //call int a=3, b=4; passingRef(&x, &y);
public void passingRef(int *x, int *y); //call int a=3, b=4; passingRef(&x, &y); |
As we see here we are passing the address of two variables, so contrary to above the changes made in function passingRef will take affect to original values.
Points to notice
- In pass by reference we are passing address value.
- when we receive the address value in passingRef we can manipulate the address and access the very next address and so on.
Coming to Java terminology
In java we generally use the term reference to point to object being passed in method or anywhere we declare it. But the term reference here do point to some address location in the heap but
- you don’t have direct access to the address value (as java doesn’t support pointers)
- You cannot manipulate the address value
So, Java has only Call by Value methodology while passing parameters in methods.
Reference although named same but terminology in JAVA is TOTALLY DIFFERENT from that of C/C++.
for more detailed view on this either write comment below or follow this link
482 total views, 2 views today
Share this On Tags: call by reference, call by value, Java, parameter passing