String Concatenation in Java

In java, string concatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java.
  • By + (string concatenation) operator
  • By concat() method
  • String Concatenation by + (string concatenation) operator

    Java string concatenation operator (+) is used to add strings.

    Example:

    class ExampleStringConcatenation{  
     public static void main(String args[]){  
       String s="Amitabh"+" Bachchan";  
       System.out.println(s);    //Amitabh Bachchan 
     }  
    }  

    Output:

    Amitabh Bachchan
    In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String concatenation operator produces a new string by appending the second operand onto the end of the first operand. The string concatenation operator can concat not only string but primitive values also.

    Example:

    class ExampleStringConcatenation1{  
     public static void main(String args[]){  
       String s=50+30+"Amit"+40+40;  
    System.out.println(s);  //80Amit4040  
     }  
    }

    Output:

    80Amit4040

    String Concatenation by concat() method

    The String concat() method concatenates the specified string to the end of current string.

    Syntax:

    public String concat(String another)

    Example:

    class ExampletStringConcatenation2{  
     public static void main(String args[]){  
       String s1="Amitabh ";  
       String s2="Bachchan";  
       String s3=s1.concat(s2);  
       System.out.println(s3);   //Amitabh Bachchan
    }
    }

    Output:

    Amitabh Bachchan

    String compare by compareTo() method

    The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.
    Suppose s1 and s2 are two string variables. If:
  • s1 == s2 :0
  • s1 > s2 :positive value
  • s1 < s2 :negative value
  • Example:

    class Examplestringcomparison3{  
    public static void main(String args[]){  
       String s1="Amit";  
       String s2="Amit";  
       String s3="Pritam";  
    System.out.println(s1.compareTo(s2));   //0  
    System.out.println(s1.compareTo(s3));   //1(because s1>s3)  
    System.out.println(s3.compareTo(s1));   //-1(because s3 < s1 )  
     }  
    }

    Output:

    0
    -15
    15