ThreaT ThreaT - 11 months ago 37
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[]) {
System.out.println("counter: " + counter);
System.out.println("test: " + test);


counter: 1

test: 0

I thought that when I increment
will automatically be incremented as well. However, it seems
is referencing
from somewhere, question is, where?

Answer Source

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.


int a = 0;
int b = a;

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


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.

test = counter;