Java String concat() method:
Java String concat() method is used to add the given String to the end of the current String.
Syntax:
public String concat(String str)
Parameter:
Str: String to be concatenated at the end of current string.
Returns:
It returns Combined String.
Example 1: Concatenating Strings one by one
public class ConcatEx1{
public static void main(String args[]){
String s1,s2,s3="null";
s1="Tutorial";
System.out.println(s1);
s2=s1.concat("And");
System.out.println(s2);
s3=s2.concat("Example");
System.out.println(s3);
}
}
Output:
Tutorial TutorialAnd TutorialAndExample
Example 2: Concatenating multiple Strings
public class ConcatEx2 {
public static void main(String[] args) {
String str1 = "Welcome";
String str2 = " to the";
String str3 = " Tutorial And Example";
// Concatenating multiple strings
String str5 = str1.concat(str2).concat(str3);
System.out.println(str5);
}
}
Output:
Welcome to the Tutorial And Example
Example 3: concatenating spaces and special characters to the string object
public class ConcatEx3 {
public static void main(String[] args) {
String str1 = "welc".concat("ome");
System.out.println(str1);
//adding the spaces
String str3 = str1.concat(" ")+"to".concat(" ").concat("the").concat(" ").concat("tutorialandexample") ;
System.out.println(str3);
//adding the special character
String str4 = str1.concat("!@#$%^&*()_+~{}:><?/*-+");
System.out.println(str4);
}
}
Output:
welcome welcome to the tutorialandexample welcome!@#$%^&*()_+~{}:><?/*-+