1

Following example:

public class MainActivity extends AppCompatActivity {
    private Button doSmth;
    private Integer myInt = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        doSmth = findViewById(R.id.doSmth);
        doSmth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Counter counter = new Counter(myInt);
                counter.incrementCounter();
                Log.i("Final Counter", myInt.toString());
            }
        });
    }
}

The according Counter-class:

public class Counter {
    Integer counter;

    public Counter(Integer counter) {
        this.counter = counter;
    }

    public void incrementCounter() {
        for (int i = 0; i < 3; i++) {
            counter = i;
            Log.i("Current Counter", counter.toString());
        }
    }
}

The console-output when the onclicklistener becomes triggered:

... integerexample I/Current Counter: 0
... integerexample I/Current Counter: 1
... integerexample I/Current Counter: 2
... integerexample I/Final Counter: 0

I would have expected that Final Counter is 2. Because myInt is an Integer-object and object are passed by reference.

But obviously a copy has become passed because myInt is still 0.

Can someone explain me the above described behaviour?

Are objects of primitives wrapper-classes somehow handled differently?

cluster1
  • 4,968
  • 6
  • 32
  • 49

2 Answers2

3

In the Counter constructor indeed a reference to the original Integer object is passed and stored.

However, the assignment counter = i; creates a new Integer object and assigns a reference to the new object to the variable counter. Thus the myInt still refers to the original object.

And by the way, Integer is immutable, meaning the value of an Integer object can never change. So even if you hold a reference it will always have the same value.

Henry
  • 42,982
  • 7
  • 68
  • 84
  • Ah, okay. As soon as I modify myInt, Java creates implicit a new one and then becomes the value of i assigned to that new Integer? – cluster1 Jan 03 '21 at 09:18
  • yes, this is called autoboxing. It happens when a primitive int is used in a place where an `Integer` is expected. – Henry Jan 03 '21 at 09:19
1

Looks like you just passed the value of myInt through the constructor and assigned that value to the new Integer counter which has nothing to do with myInt.

That's why myInt's value is still 0.

I think you can have a look at this to have a better understanding regarding this matter.

Dinkkk
  • 72
  • 1
  • 6