String immutability. Do I have to reassign it to t

2020-05-09 19:59发布

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?

标签: java
8条回答
SAY GOODBYE
2楼-- · 2020-05-09 20:25

The first one is how you do it.

查看更多
Juvenile、少年°
3楼-- · 2020-05-09 20:35

You need to assign:

str = str.toLowerCase();

These methods return a new String - they don't modify the String.

查看更多
混吃等死
4楼-- · 2020-05-09 20:36

You should use the first version

str = str.toLowerCase(); // the right way

since it replaces the reference to the old String instance with a reference to the new all lowercase instance. The second version

str.toLowerCase(); // the wrong way

does not change the String instance referred to by str (which is what immutability means), but returns a new all lowercase instance which is then ignored.

查看更多
爷的心禁止访问
5楼-- · 2020-05-09 20:38

String are immutable

Yes, by your own admission. An immutable object is one that does not allow its state to be changed. This includes String objects.

Then:

str.toLowerCase();

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.)

str = str.toLowerCase();

However, there is no requirement that the same variable is re-assigned to. Consider the following examples, which may be entirely valid in context:

String normalizedTitle = title.toLowerCase();
foo.setTitle(normalizedTitle);
// or, skip normalizedTitle, etc.
foo.setTitle(title.toLowerCase());

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).

查看更多
Melony?
6楼-- · 2020-05-09 20:38

Only the first will work; the String.toLowerCase() returns is a new string, it doesn't change anything in place.

查看更多
可以哭但决不认输i
7楼-- · 2020-05-09 20:38

First one. Re-assign it.

str= str.toLowerCase();
查看更多
登录 后发表回答