xxxxxxxxxx
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
Output:Sachin Tendulkar
xxxxxxxxxx
public class ConcatenationExample {
public static void main(String args[]) {
//One way of doing concatenation
String str1 = "Welcome";
str1 = str1.concat(" to ");
str1 = str1.concat(" String handling ");
System.out.println(str1);
//Other way of doing concatenation in one line
String str2 = "This";
str2 = str2.concat(" is").concat(" just a").concat(" String");
System.out.println(str2);
}
}
xxxxxxxxxx
StringBuilder stringBuilder = new StringBuilder(100);
stringBuilder.append("Baeldung");
stringBuilder.append(" is");
stringBuilder.append(" awesome");
assertEquals("Baeldung is awesome", stringBuilder.toString());
xxxxxxxxxx
public class Concat {
String cat(String a, String b) {
a += b;
return a;
}
}
xxxxxxxxxx
public class Main
{
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "People";
String str3 = str1 + str2; // Concatinating two string variables
System.out.println(str3);
System.out.println(str3 + "!!!"); // Concatinating string variable with a string
}
}
xxxxxxxxxx
// adding strings with the plus is not elegant use 'String.format()' for it
String s1 = "text1";
String s2 = "text2";
String s3 = "easy: " + s1 + " " + s2;
System.out.println( s3 );
//A "better" way to do this:
String s4 = String.format( "better: %s %s", s1, s2 );
System.out.println( s4 );
// gives:
easy: text1 text2
better: text1 text2
xxxxxxxxxx
// StringBuilder
String stringBuilderConcat = new StringBuilder()
.append(greeting)
.append(" ")
.append(person)
.append("! Welcome to the ")
.append(location)
.append("!")
.build();
xxxxxxxxxx
@State(Scope.Benchmark)
public static class MyState {
int iterations = 1000;
String initial = "abc";
String suffix = "def";
}
@Benchmark
public StringBuffer benchmarkStringBuffer(MyState state) {
StringBuffer stringBuffer = new StringBuffer(state.initial);
for (int i = 0; i < state.iterations; i++) {
stringBuffer.append(state.suffix);
}
return stringBuffer;
}
@Benchmark
public StringBuilder benchmarkStringBuilder(MyState state) {
StringBuilder stringBuilder = new StringBuilder(state.initial);
for (int i = 0; i < state.iterations; i++) {
stringBuilder.append(state.suffix);
}
return stringBuilder;
}