membersound
membersound

Reputation: 86747

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.

Upvotes: 2

Views: 2180

Answers (4)

user1075613
user1075613

Reputation: 744

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.

Upvotes: 1

Dan Temple
Dan Temple

Reputation: 2764

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.

Upvotes: -1

assylias
assylias

Reputation: 328619

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

int[] counter = new int[1];

counter[0]++;

Upvotes: 5

M A
M A

Reputation: 72854

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++;
   }
   ...
}

Upvotes: 4

Related Questions