Variable as Java Method Argument

Asked

Viewed 296 times

2

Do you pass a variable as an argument of a method not its value, but the instance itself, every change made in the argument applies the variable? Just like it works in Javascript?

1 answer

3


Yes and no. Let’s conceptualize well.

To variable cannot be passed, it is a local concept that indicates storage of something. The instance can yes.

In types by value the variable contains the instance itself. In reference types a pointer is passed that points to an instance (technically the pointer is still an instance as well, but not the main object).

Reference types often 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’s not guaranteed to be like this. Some guys, so-called immutable, can create a new instance (String).

All classes that have their values passed as argument will behave like this, like Javascript does with their objects.

But note that, like Javascript, Java has types per value that are copied and changes in it will not be reflected in the variable used.

Java has the "advantage" of having classes equivalent to primitive ones. So if you want to pass one, pass one Integer in place of a int.

If a String, which is a class, but which has semantics of type by 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 it 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 such a case is to wrap (box) in another type by reference, thus the pointer of the string is sent by reference and will be changed in 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 campo nome será mudado

It’s not the same language, but you might have a better idea of how it works in:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.