First look at a small program
The output of the main function does not output 3 as expected. Instead, it outputs the initialized value 0.
This is becauseSimilar to string, all packaging classes are final classes, that is, immutable classes.. Although code A seems to have changed the counter value, it actually creates another object and points the reference of the counter parameter in the method to the newly created object, because it is a different reference, it does not have any impact on references outside the method. The memory diagram is as follows:
When you first enter the method:
After counter = counter + 1 is executed, because integer is an immutable class, to change its value, it actually creates a new object, so the memory figure is as follows:
Integer is an immutable class. after entering a method, changing the value in it will not affect references outside the method.