Reputation: 51
In my text book there was nothing that seemed weird, to me at least, which is say that I have a class and this class has a method that takes an array on integer(or anything) then sort it with any kind of algorithm. The weird part is he just calls the method and passes the array, and the method will not return anything it is void.
.....
sort(anArray)
.....
.....
.....
public void sort(int[] array)
.....
and that will immediately update anArray to be sorted. What I have in mind is the method will return another array which is the same array but sorted so it will be
.....
arrayx = sort(anArray)
.....
.....
.....
public int[] sort(int[] array)
.....
can you please explain to me the differences.
Upvotes: 1
Views: 70
Reputation: 1221
1) In this case your function returns void
(nothing) and it means this function with side effect
public void sort(int[] array)
2) Your function returns int[]
, and it may be pure function
(it's depends of function code)
public int[] sort(int[] array)
About side effect
and pure function
:
Upvotes: 0
Reputation: 6349
sort(anArray);
...
public void sort(int[] array) { ... }
In this example, the array that has been passed in is being modified. Nothing is returned.
This can be done because of how Java handles arrays as parameters to functions.
You should look at this question which explains how array parameters work: Are arrays passed by value or passed by reference in Java?
arrayx = sort(anArray);
...
public int[] sort(int[] array) { ... }
In this example, a new array is created inside the function and then returned.
Because the original array is not being modified, you need to store the result of the function call in a variable to obtain the sorted array.
Upvotes: 1