Java String concat() method explained | technical-arbaab

Java String concat() method explained

It is a predefined function which is present in the Java.lang.String package. It is used to concatenate two strings or it will concatenate the second string in the ending of first string or you can say that it will just append (insert at last) the second string to the first string and returns the appended string.

Syntax of concat() function

 public class ConcatString {  
      public static void main(String[] args)  
      {  
           String s = "hello";  
           s=s.concat("Jack");  
           System.out.println(s);  
      }  
 }  
Output:
 helloJack  
If you will do like this it does not work-
 public class ConcatString {  
      public static void main(String[] args)  
      {  
           String s = "hello";  
           s.concat("Jack");  
           System.out.println(s);  
      }  
 }  

Output:

 hello  

you have to assign it to the string variable but you can also do like this-

 public class ConcatString {  
      public static void main(String[] args)  
      {  
           String s = "hello";  
           System.out.println(s.concat(" Jack"));  
      }  
 }  
Output:
 hello Jack  

Example 01 of concat() function

let's see an example where we are concatenating some symbol with the string-

 public class ConcatString {  
      public static void main(String[] args)  
      {  
           String s1 = new String("hello ");  
           String s2 = new String("technical");  
           String s3 = new String("arbaab");  
           String s4 = new String("-");  
           String s6 = s2.concat(s4);  
           String s7 = s6.concat(s3);  
           String s8 = s1.concat(s7);  
           System.out.println(s8);  
      }  
 }  
Output:
 hello technical-arbaab  

Example 02 of concat() function

let's see an example where we are concatenating some spaces with the string-

 public class Concatstrings02 {  
      public static void main(String[] args)  
      {  
           String s1 ="one";  
           String s2 = "two";  
           String s3 = "three";  
           String s4 = "four";  
           String s5 = "five";  
           String s6 = s1.concat(" ").concat(s2).concat(" ").concat(s3).concat(" ").concat(s4).concat(" ").concat(s5);  
           System.out.println(s6);  
      }  
 }  
Output:
 one two three four five  

Example 03 of concat() function (concatenating special characters)

let's see an example where we are concatenating some special symbols as a string-

 public class ConcatStrings03 {  
      public static void main(String[] args)  
      {  
           String s1 = "@";  
           String s2 = "#";  
           String s3 = "$";  
           String s4 = "%";  
           String s5 = "&";  
           String s6 = s1.concat(" ").concat(s2).concat(" ").concat(s3).concat(" ").concat(s4).concat(" ").concat(s5);  
           System.out.println(s6);  
      }  
 }  
Output:
 @ # $ % &  

Comments