Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment an integer by reference?

Is it possible to increment an integer value by reference?

int counterA = 0;
int counterB = 0;

int counter = (condition) ? counterA : counterB;
//use counter
counter++;

Result: both counterA + counterB will remain = 0, instead being incremented.

like image 630
membersound Avatar asked Mar 28 '26 21:03

membersound


2 Answers

As an alternative to an int holder you can also use an array:

int[] counter = new int[1];

counter[0]++;
like image 196
assylias Avatar answered Apr 01 '26 08:04

assylias


int is a primitive type so there is no reference being assigned, only values. You can wrap it in a class:

public class IntegerHolder {
   private int value;

   public IntegerHolder(int value) {
       this.value = value;
   }

   public void increment() {
       value++;
   }
   ...
}
like image 31
M A Avatar answered Apr 01 '26 07:04

M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!