Contents

Methods For concat Strings

Using +

When one of the left and right variables is of type String, the plus method can be used to convert the two variables into strings and concatenate them.

1
2
3
4
5
6
7
8
String a = "hello";
int b = 1;
String c = a + b;

/**
 * result:
 * hello1
 * /

Using concat()

When two variables are both String and both not null, it can be used.

1
2
3
4
5
6
7
8
String a = "hello";
String b = "world";
String c = a.concat(b);

/**
 * result:
 * helloworld
 * /

Using append() (recommend)

When there are more than two Strings, we can consider using this method, to avoid creating temporary string variable.

1
2
3
4
5
6
7
8
9
StringBuilder sb = new StringBuilder("hello");
sb.append(",");    
sb.append("world");    
String z = sb.toString();

/**
 * result:
 * hello,world
 * /

we can also set an estimated capacity when instantiating the StringBuilder Class to reduce performance overhead from expanding buffer space.

1
StringBuilder sb = new StringBuilder(a.length() + b.length());

!! The + concatenation of strings in Java is implemented by using append() !! So, using StringBuilder is more efficient.