Beware Strings continue to be immutable after so many years(java newbies)
This post is just a reminder targeting new Java developers rather than experienced or senior people. Lately I have been reading and browsing on lots of different Java projects - part of my day to day duties. In order to add some fun to this activity I usually engage tools like FindBugs and PMD to check the code and it's underlying quality.
I am amazed about the fact that the most common error I encounter- browsing Java code is the mistake developers do, to forget the immutable nature of Strings!
'String aStr = "An Apple"; aStr.trim();'
Many developers think that since they have called .trim() or split() or any other method that alters the state of the String this change will be reflected to the object as soon as they access the very same String on a subsequent call. This is so wrong. If you want to really use the altered version of the (aStr) object you should assign a new variable. The original (aStr) will never change.
'String aStr = "An Apple"; String aStrAltered =aStr.trim();'
Check the full problem list of Findbugs and you will find my champion of all in occurrences on the following code: _RV: Method ignores return value (RV_RETURN_VALUE_IGNORED)