2

Maybe a stupid question but I can't see the answer. Let's say we have this simple example:

Integer a = 10;
a+=4;

From what I have read and tried behind the scenes is happening something like this:

Integer a = 10;
a = new Integer (a+4);
  • Why does Java need to create a new instance and then override the previous reference value with a new one?
  • Does Integer (and other reference types variables (Byte, Character)) follow the same principle as Strings?
  • Is not this a performance issue if you want to change the value of a variable and you expect to keep the current reference and to update only the value and what you get is a brand new object?
  • Reflect the image below (in big lines) reflect what happens?

enter image description here

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Adrian
  • 947
  • 1
  • 12
  • 24
  • As I remember there is a cache mechanism for specific range of integers – Gurkan İlleez Aug 07 '19 at 18:37
  • it has to do an _un-box_ to perform the sum, then _box_ back to assign to the reference back. – Eugene Aug 07 '19 at 18:38
  • 2
    Even worse: the second line should be `a = new Integer(a.intValue() + 4)`. Boxing, as Eugene said. It’s introduced to make code more readable. But that still requires you to know what happens under the hood. – Michiel Leegwater Aug 07 '19 at 18:44
  • 3
    In short, if you don't like the references, use `int` instead of `Integer`. – markspace Aug 07 '19 at 18:46
  • 3
    @markspace it goes beyond that. Imagine you design a class that must retrieve results from a rdbms, the column mapped to your field is an int but it may have `NULL` values. If this is the case, `Integer` is the way to go. Otherwise, use `int`. – Luiggi Mendoza Aug 07 '19 at 18:48
  • @LuiggiMendoza but why is not happening the same with custom objects (classes)? Let's say we have a class with a public int value. If I send this object as a parameter to a function and I change this value this will be reflected also on the caller, but if I do this with reference types (Integer) this is not the case. Is this because reference data types are design to be immutable and custom objects not? – Adrian Aug 08 '19 at 06:29
  • 1
    That's because immutability. When a class is designed as immutable, objects cannot modify their state. If you want to modify the state of an immutable object, what you get is a new object with the new desired state. While you may think this is a waste of resources and memory, it provides enormous benefits for lots of cases e.g. multi threaded applications and functional programming. – Luiggi Mendoza Aug 08 '19 at 06:38

0 Answers0