ThreaT ThreaT - 2 months ago 7
Java Question

Incrementing an Integer variable doesn't affect another referencing the same object

I always understood static variables to share one instance whenever they were referenced. I wanted to put this to the test but the results were different than I had expected.

static Integer counter = 0;
static Integer test = counter;

public static void main(String args[]) {
counter++;
System.out.println("counter: " + counter);
System.out.println("test: " + test);
}


output:


counter: 1

test: 0


Since
test
references
counter
I thought that when I increment
counter
then
test
will automatically be incremented as well. However, it seems
test
is referencing
0
from somewhere, question is, where?

Answer

Since test references counter

This assumption is false. In Java, you cannot reference variables. What is stored in a variable is a value. That value can either be a primitive type value or a reference type value. In the case of primitives, the value is the value of the primitive. In the case of reference types,

The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

In

int a = 0;
int b = a;

the variable a is evaluated to produce a value, 0, and that value is stored in b.

In

Integer a = 0;
Integer b = a;

0 is converted to an Integer through Integer.valueOf(int) and the value, a reference to an Integer object is stored in a. Then a is evaluated, producing the value of that reference to an Integer object, and that value is stored in b.

This is the same concept discussed in

Also, the fact that the variables are static is irrelevant.

The only way around this is to update test manually i.e.

counter++; 
test = counter;
Comments