+ 2
How can we call by reference in java ?
I searched in net , call by reference is not possible in case of java . But explanation is not sufficient . Can someone provide me a code and explain that code little bit . What is the substitute for this call by reference , if not possible .
6 Answers
+ 14
You can't use pointer in Java, but you can pass reference of a non-primitive type to a void method and change it's content. Non primitive means object, array etc. Here is a sample code:
https://code.sololearn.com/c613pBjuPn1q/?ref=app
+ 13
@Om, okay we'll ask all people in the world, now stop trolling please. It's a help seeking post -_-
+ 6
note* I refer to passing by reference here, but calling by reference will require the same functionality.
Primitive datatypes do not and cannot be passed by reference. Instead, they are passed by value.
For example
void a(){
int age;
b(age);
}
void b(int age){
age = 4;
}
The function from b is not changing the same variable as from function a. There is no way to pass a primitive datatype by reference in Java. Only objects are passed by reference.
The usual way to deal with this are getters and setters. For example:
void a(){
int age = 0;
age = b(age);
}
int b(int age){
return age+5;
}
Though there is a 'hack'. You can pass arrays by reference since they're objects. So if you really wanted to you could use an array for the variable. This will take up more memory, so it's likely not as practical.
+ 3
I might have a solution and I'm not a troll. Was just trying to have some fun. Sorry
- 2
ask my friend Hayes
- 4
refer to Steve Jobs for the answer