String Concatenation in java is a real topic for every programmer. Many of the programmers are not yet aware of what are the ways to concatenate string in java. What are the ways...
- String.concat().
- Normal Concatenation using (+) operator.
- String Buffer
- StringBuilder
1. Using Concatenation Operator(+):-
It's the easy way to do the job. Ex:- String s = "hai how what when"+"where why"+"think or not" ; But just think if you are using this in a for loop. Each time String will create a new object inside the string pool. It will create performance leakage.
2.Using StringBuffer and StringBuilder append():-
Using the String Buffer or String Builder. StringBuilder str = new StringBuilder().append("hai when where").append("why how what").toString();
Program for Concatenation in java:
String firstname = "Sachin"; String lastname = "Tendulkar"; Use + operator to concatenate String String name = firstname + " " + lastname; System.out.println(name);// first way
StringBuilder StringBuilder sb = new StringBuilder(14);
sb.append(firstname).append(" ").append(lastname); System.out.println(sb.toString()); //second way
StringBuffer StringBuffer sBuffer = newStringBuffer(15);
sBuffer.append(firstname).append(" ").append(lastname); System.out.println(sBuffer.toString());//third way
Out Put:
Sachin Tendulkar
Sachin Tendulkar
Sachin Tendulkar
- String.concat().------- 1358 ms
- Normal Concatenation using (+) operator. --------6568 ms
- String Buffer ------------- 2.8 ms
- StringBuilder -------------- 2.4 ms
So better to use StringBulder for larger Concatenations and inside for loops.