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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, by your own admission. An immutable object is one that does not allow its state to be changed. This includes
Stringobjects.Then:
Creates a new string of lower-case characters and does not use the result. This is likely a “bug” in this case as
strstill 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).