Just few typical mistakes developers do when dealing with Strings. It's common stuff and everybody knows that, but for some reasons I still find such things (even written by myself :-)).
1. Checking empty string
In old days (version 1.5 and lower) we used String.equal(""), but 1.6 brought us String.IsEmpty which is better and faster.
// wrong/slow
if (name.equals("")) {
// correct/fast
if (name.isEmpty()) {
2. Concatenation
Method
String.concat creates new String object, it's OK to use it when you do operation only once, otherwise use operator + += operators (see below why).
String s = "Hello ".concat("new").concat(" world!"); // "Hello new world!"
Using operators + and +=, they do not use
String.concat method but
StringBuilder and it's important to know what it means to us.
String s = "Hello " + "new" + " world!"; // "Hello new world!"
What actually happens when you use + operator is StringBuilder used:
String s = new StringBuilder().append("Hello ").append("new").append(" world!").toString(); // "Hello new world!"
So conclusion - it's ok to use concat if you do one time operation, for any other situation I would recommend to use + or +=.
3. String Formatting
Very often in order to format string people either concatenate the string to achieve result or do replace or invent something else. I do it as well sometimes (what a shame!). Instead we should use String.format method to do that.
int n = 10;
// wrong
String s = "I have " + Integer.toString(10) + " books";
// wrong
String s = "I have #num books".replace("#num", Integer.toString(10));
// correct
Strig s = String.format("I have %d books", n);
I would be glad to hear other typical mistakes we do with String object! So please share your experience.