Tuesday 17 January 2012

Concatenating chars using + operator

Lets look at the following code snippet:
char c1 = 'A';
char c2 = 'B';

Lets try + operator first:

System.out.print(c1+c2);

Can you guess the output....it is not 'ab' but it 131 (= 65+66) i.e. sum of ascii value of 'A' and 'B'.

So it is not parallel to concatenating strings, but how should we concatenate 2 char's ?

Solution 1: Append using StringBuilder
StringBuilder sb = new StringBuilder('a').append('b').append('c');
System.out.println(sb.toString);

Solution 2 : Neater style using + operator for string concatenation
System.out.println("" + char1 + char2 + char3...);

Solution 3 : Using char array
System.out.println(new String(new char[]{a,b,c}));

Comparing the approaches
You should generally use second approach, third doesn't seem normal though and first approach looks like optimization flick. The approach selection depends on the char's having values at compile time or they are provided at the run time. So first read this article.

If the characters are constant, this is fine:
String s = "" + 'a' + 'b' + 'c';

If however they aren't, consider this:

String concat(char... chars) {
  if (chars.length == 0) {
    return "";
  }
  StringBuilder s = new StringBuilder(chars.length);
  for (char c : chars) {
    s.append(c);
  }
  return s.toString();
}

as an appropriate solution.

However some might be tempted to optimise:
String s = "Name: '" + name + "'"; // String name;
into this:
String s = new StringBuilder().append("Name: ").
append(name).append("'").toString();
While this is well-intentioned, the bottom line is DON'T.

Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.

For low-level optimisation the compiler is better at optimising code than you are.

Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.

Caution for approach 3

System.out.println(new String(new char[]{a,b,c}));
Though String constructor provides method of concatenating char's, but + operator don't allow so....
So the output of this approach will be :

char alphabets =  {a,b,c};
System.out.println("Alfa "+alphabets);

Output expected may be Alfa abc but actually it is Alfa [C@16f0472.To get the above effect use following :
System.out.println(letters + " easy as " +String.valueOf(alphabets));

No comments:

Post a Comment