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);
}
}
public class Concat {
String cat(String a, String b) {
a += b;
return a;
}
}
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
}
}
// 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
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
Output:Sachin Tendulkar
// StringBuilder
String stringBuilderConcat = new StringBuilder()
.append(greeting)
.append(" ")
.append(person)
.append("! Welcome to the ")
.append(location)
.append("!")
.build();
class Main {
public static void main(String[] args) {
// create first string
String first = "Java ";
System.out.println("First String: " + first);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
-By using (+) operator
-By using concatenate method (concat()).
String strconcat3=strconcat2.concat(strconcat);
-By StringBuffer
-String strconcat= new StringBuilder().append("matt")
.append("damon").toString();
-By StringBuilder
- String strconcat2= new StringBuffer()
.append("matt").append("damon").toString();