In fact return
does not come to be a specific concept of object orientation. It is part of the syntax of Java and many other languages and is a key word used to return to the code where the method was initially called.
A method of any type returns when it encounters return
followed by its respective type; Home
A method of type void
returns when it finds return;
or when it reaches the end of it.
But your question can be better explained by the types of Java data and passing arguments by value or reference .
Argument passing by value
When you pass only primitive type arguments (int, float, double, long, short, char, or byte) to a method, they are passed por valor
. That is, a% w of% of that variable is made within the scope of the method and even if you change it, nothing will happen to the original variable you passed as the argument first.
public static int metodoSomaDois(int argumento) {
//Uma cópia do seu argumento recebe ele mesmo + 2
//Sendo assim vc precisa retornar ele caso
//queira atribuir o seu valor alterado à uma outra variável externa
argumento += 2;
return argumento;
}
Example:
int original = 5;
metodoSomaDois(original); //Nada vai acontecer já que vc não atribuiu o retorno do método a nenhuma outra variável e a original permanece 5.
original = metodoSomaDois(original); //Agora a variável original vai receber o valor retornado do método
Argument passing by reference (your case)
Arguments of non-primitive types (arrays, objects, and so on) are passed by cópia
. This means that the object itself is passed (more precisely a pointer to that object) and not a copy. That is, any change made to that object within the scope of the method will also change the object that was originally passed as an argument.
public static void metodoAlteraValores(int listaPorArgumento[]) {
//Como esta sendo passado por referência
//os valores da lista original vão ser alterados também sem a necessidade de atribuir o retorno
for (int i = 0; i < 3; i++)
listaPorArgumento[i] = 10;
}
Example:
int lista[] = {5, 5, 5};
for (int i : lista)
System.out.print(i + ", "); //Exibe 5, 5, 5,
metodoAlteraValores(lista); //Altera os valores pra 10 sem precisar de atribuir a nenhuma outra variável
for (int i : lista)
System.out.print(i + ", "); //Exibe 10, 10, 10, (o que mostra que a lista original foi alterada)
Conclusion
This shows that your first example is the right one and why. Home
Briefly, referência
will be used when you need to return a value that has to be assigned to some variable, and is not required when you directly change an object that is passed by reference.
Note that it is possible to return an object of a non-primitive type, which can be assigned to a variable of the same type. Usually this happens when you, for example, want to change an array without changing the original. Home
Therefore, the ideal, for your case, would be to create an object of the same type within the method and make a clone of the original that can be changed and then returned.