2

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.

M A
  • 71,713
  • 13
  • 134
  • 174
membersound
  • 81,582
  • 193
  • 585
  • 1,120

4 Answers4

4

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++;
   }
   ...
}
M A
  • 71,713
  • 13
  • 134
  • 174
4

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

int[] counter = new int[1];

counter[0]++;
assylias
  • 321,522
  • 82
  • 660
  • 783
1

Short answer : use AtomicInteger :

AtomicInteger counterA = new AtomicInteger();
AtomicInteger counterA = new AtomicInteger();

AtomicInteger counter = (condition) ? counterA : counterB;
counter.incrementAndGet();

In Java, all variables are pass-by-value, including primitive types like integer (and even objects but it may be confusing here, just check there).

You could be tempted to use Integer but wrapper classes are immutable. Instead you can use AtomicInteger which is mutable.

Community
  • 1
  • 1
user1075613
  • 725
  • 9
  • 13
0

As an alternative to a wrapper object (the answer you've been provided by other users) you could just use an if-else statement and increment the values directly:

int counterA = 0;
int counterB = 0; 

if(condition)
{
    counterA++;
}
else
{
    counterB++;
}

This can become too wieldy if you have more than 2 counters though.

Dan Temple
  • 2,736
  • 2
  • 22
  • 39