Because there are immutable and mutable classes.
String
, as another answer points out, is an immutable class. Their value always stays the same once a String is created.
If you have an ArrayList<Integer>
object, you can use its add
function to add another Integer to the list. The add
function changes the list in-place, instead of returning a new list. An ArrayList is mutable.
Response to Edit:
For your groovy example, probably its designers sat down and noticed that more often one would want a new list that contains the reversed result, and keep the old list untouched. (Why? I don't know). On the other side, they may have noticed there are more cases where you want not to have a new list which contains the sorted result. So it does its job in-place. But i don't know and haven't used groovy before, so just a guess.
In Ruby, i have heard there is a notion for this: Functions that change objects in-place have an exclamation written after them, and functions that return the result as a new object have no exclamation mark:
newObj = obj.sort(); // new sorted list is returned
obj.sort!(); // obj is sorted in-place