I'm very new to Java, I had decent experience with C++ and Python. Now, coming from C++, I miss pass by reference a bit. I wrote code for the approach I want to take:
package bs;
public class Main{
private int a = 1;
private int b = 11;
public void inc(int i){
if (i < 6){
inc_all(this.a);
}
else{
inc_all(this.b);
}
}
private void inc_all(int prop){
prop++;
}
public void display(){
System.out.println(a + " " + b);
}
public static void main(String[] args){
Main car = new Main();
int i = 1;
while( i < 11){
car.inc(i);
car.display();
i++;
}
}
}
Now, I can write two different functions for incrementing a, b, but I want to write only function and pass the the attribute(a
or b
) depending on the scenario. In this case, the attributes are clearly not getting incremented (thanks to pass by value).
How do I solve this problem without making a
and b
arrays (I know arrays are always pass by reference)?