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)?
You cannot. Period. That's a java thing; it's intentional.
In general you should program such that callers cannot change things and that this is fine. For example, instead of:
/** After calling this, `prop` has been incremented */
public void increment(int prop) {
// this method cannot be written in java, at all.
}
you should have:
/** Returns the value that immediately follows {@code prop} in its numeric domain. */
public int increment(int prop) {
return prop + 1;
}
If you want methods to be able to make changes that callers can witness, you must pass references to non-immutable objects, instead:
AtomicInteger x = new AtomicInteger(5);
increment(x);
System.out.println(x.get()); // this prints '6'
public void increment(AtomicInteger x) {
x.incrementAndGet();
}
The difference here is that AtomicInteger
is mutable, whereas raw ints are not. If you use x.
, you are driving over to the house (x is an address to a house, not a house!), entering, and messing with it. With x =
, you are making changes to the note upon which you scribbled down the address someone told you over the phone. This has no effect whatsoever on either the house, or the address book of the person who phoned you up to tell you the address - it changes only things you can see (you = method), nothing more. So, if you want changes to be visible, think dots (or array brackets), don't use =
.