How do you pass a variable as argument of a method not its value, but the instance itself, any change made in the argument applies to the variable? So how does JavaScript work?
How do you pass a variable as argument of a method not its value, but the instance itself, any change made in the argument applies to the variable? So how does JavaScript work?
Yes and no. Let's conceptualize well.
The variable can not be passed, it is a local concept that indicates storage of something. The instance may.
In types by value, the variable contains the instance itself. In types by reference, a pointer is passed that points to an instance (technically the pointer is not an instance as well, but not an object).
Types by reference usually allow their data to be changed and when the method is finalized the changes will be reflected in the original variable used as argument. But it is not guaranteed to be so. Some types, called immutable , can create a new instance.
All classes have their values passed as an argument they will behave as well as JavaScript does with their objects.
But note that just like JavaScript, Java has value types that are copied and changes in it will not be reflected in the variable used.
Java has the "advantage" of having classes equivalent to primitives. So if you want to pass one, pass Integer
instead of int
.
String
, which is a class but has type semantics per value, equal to JavaScript, and some change is made to it, the code will not see the changes made at the end of the method code, since which is not the object that was changed, another object was created and pointed to it in the local variable (parameter). The argument is not changed, the consumer will not see anything done within the method. The only solution in this case is to envelop in another type by reference, so the string pointer is sent by reference and will be changed in the argument.
void exemplo(int x) { x = 1; } //quem chamar este método não terá seu valor mudado para 1
void exemplo(Integer x) { x = 1; } //quem chamar este método terá seu valor mudado para 1
void exemplo(String x) { x = "x"; } //quem chamar não terá seu valor mudado para "x"
void exemplo(MinhaClasse x) { x.setNome("João"); } //o atributo nome será mudado
It's not the same language, but you can get a better idea of how it works in: