Wednesday, September 07, 2011

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)

3 comments:

  1. The same thing happens with BigDecimal, and all immutable objects. As you said, FindBugs catches such mistakes.

    ReplyDelete
  2. yeap correct...it seems that String is the most common data type of all for such operations :D

    ReplyDelete
  3. ΕΦΙΑΛΤΗΣ ΠΑΛΙ ΜΕ ΤΙΣ ΠΑΝΕΛΛΗΝΙΕΣ! :
    http://anisixos.blogspot.com/2011/09/blog-post_07.html

    Αν θες διαβασε το.
    Περιμενω εντυπωσεις και σχολια.
    Ευχαριστω.

    ReplyDelete