Strings are immutable, does it mean that i always have to do something like that with a string passed to a method?
str= str.toLowerCase();
or is
str.toLowerCase();
fine? I tried the second one and it doesn't give me any errors, why?
Strings are immutable, does it mean that i always have to do something like that with a string passed to a method?
str= str.toLowerCase();
or is
str.toLowerCase();
fine? I tried the second one and it doesn't give me any errors, why?
The first one is how you do it.
You need to assign:
These methods return a new String - they don't modify the String.
You should use the first version
since it replaces the reference to the old
String
instance with a reference to the new all lowercase instance. The second versiondoes not change the
String
instance referred to bystr
(which is what immutability means), but returns a new all lowercase instance which is then ignored.Yes, by your own admission. An immutable object is one that does not allow its state to be changed. This includes
String
objects.Then:
Creates a new string of lower-case characters and does not use the result. This is likely a "bug" in this case as
str
still evaluates to the original string object (which was not changed because it is immutable).There is no compiler error because Java has no way of knowing that the return value was "supposed to be used". There are times when a method is called for side-effects, even if it also returns a value*. This could be judged to be an error in some pure languages (those without side-effects), but it is not possible in a language with side-effects in general. Some static analysis tools -- not javac, which is just a compiler with a primitive set of warnings -- are capable of detecting such bugs as the above by applying additional heuristic rules.
Ditto, but assigns the new string to the same variable: (Variables are not values/objects.)
However, there is no requirement that the same variable is re-assigned to. Consider the following examples, which may be entirely valid in context:
Happy coding.
*An example of relatively common method that causes a side-effect and returns a value that is normally ignored is
List.remove(int)
.Only the first will work; the
String.toLowerCase()
returns is a new string, it doesn't change anything in place.First one. Re-assign it.