What happened
What happens logically after the first assignment is this:
ItdoesnotmatterthatyouusednewInteger(1)
orsimply1
,theresultisthesame.
Whenyoucalledthemuda
method,whathappensisthis:
Andfinally,whenthesecondassignmentoccurs,wehaveanewvalueforn
:
Whenthemuda
methodends,then
variableandthe3
valuearediscardedandthestateremainsthesameasthefirstimage.
Whathappenstoanarray
Whenusinganarray,youareactuallyreferencinganobjectthatcontainsmultiplevalues:
Whenyoupassthistothemuda
method,youhavetwovariablespointingtothearray:
Whenchanginganelement,thetwovariablesremainpointingtothesamearray,buttheinternalstateofthearrayisaffected,changingoneofitsvalues.
Finally,afterexecutingthemethod,thek
variableremainsintactandunchanged,however,theinternalstateoftheobjectitreferenceshasbeenaffected:
Using a wrapper object
The DannE response tells you how you can use an object whose internal value can be affected.
I'm not going to draw this because it would be exactly the same sequence using the vector.
In fact, many people use vectors or maps as an easy way to change parameters, but this is not very common or good practice.
Considerations
Immovable objects such as Integer
and String
and references that can not be affected in methods (such as pointers in C) exist for a very simple reason: keep developers healthy .
I say this because although it leaves the language more restricted, it also avoids numerous problems where values are unexpectedly modified by obscure methods. In a language that claims to be easy and universal, this is a small price to pay.
In addition, the basic solution to this case is extremely simple. Just return the modified object:
public static void main (String[] args) {
Integer k = 1;
Integer k1 = incrementa2(k);
System.out.println(k1);
}
public static Integer incrementa2(Integer n) {
return n + 2;
}