Java string concat() method concatenates multiple strings. This method appends the specified string at the end of the given string and returns the combined string. We can use concat() method to join more than one strings.
The concat() method signature
public String concat(String str)
This method concatenates the string str at the end of the current string. For example – s1.concat("Hello");
would concatenate the String “Hello” at the end of the String s1
. This method can be called multiple times in a single statement like this
String s1="Beginners"; s1= s1.concat("Book").concat(".").concat("com");
The value of s1 would be BeginnersBook.com after the execution of above statement.
Java String concat method Example
In this example we will see two ways of doing String concatenation using concat() method.
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); } }
Output:
Welcome to String handling This is just a String
Another example of Java String concat method
As we have seen above that concat() method appends the string at the end of the current string. However we can do a workaround to append the specified string at beginning of the given string.
public class JavaExample { public static void main(String args[]) { String mystring = ".com"; String mystr = "BeginnersBook".concat(mystring); System.out.println(mystr); } }
Output:
Leave a Reply