Friday, August 27, 2010

Immutable strings in Java

Strings are said to be immutable in Java.Immutability refers to ability toprevent change in value.
It means whenever you change the value of String, you create a new object and make that variable refer to new object.Appending a string is also a same kind of operation internally.

Each time you use "+" operator or ( String.concat() ) , a new string is created, old data is copied and new data is appended. Old string will be garbage collected.

When to use "+":

1). Multiline Strings

String text=
    "line a\n"+
    "line l\n"+
    "line b";
2) Short messages
System.out.println("x:"+x+" y:"+y); 

When you have multiple string blocks to concat use StringBuilder or 
StringBuffer( if multithreading is used ) class.

1 comment:

  1. If you'll be involved in any l10n projects, I recommend to try a software localization tool like this one that can simplify the users' workflow. It can be very helpful for developers and translators alike. Give it a try!