Thursday, 26 March 2015

String Concatenation in Java

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:
  1. By + (string concatenation) operator
  2. By concat() method

1) String Concatenation by + (string concatenation) operator

Java string concatenation operator (+) is used to add strings. For Example:
  1. class TestStringConcatenation1{  
  2.  public static void main(String args[]){  
  3.    String s="Sachin"+" Tendulkar";  
  4.    System.out.println(s);//Sachin Tendulkar  
  5.  }  
  6. }  

Output:Sachin Tendulkar
The Java compiler transforms above code to this:
  1. String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();  
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. For Example:
  1. class TestStringConcatenation2{  
  2.  public static void main(String args[]){  
  3.    String s=50+30+"Sachin"+40+40;  
  4.    System.out.println(s);//80Sachin4040  
  5.  }  
  6. }  

80Sachin4040

Note: After a string literal, all the + will be treated as string concatenation operator.

2) String Concatenation by concat() method

The String concat() method concatenates the specified string to the end of current string. Syntax:
  1. public String concat(String another)  
Let's see the example of String concat() method.
  1. class TestStringConcatenation3{  
  2.  public static void main(String args[]){  
  3.    String s1="Sachin ";  
  4.    String s2="Tendulkar";  
  5.    String s3=s1.concat(s2);  
  6.    System.out.println(s3);//Sachin Tendulkar  
  7.   }  
  8. }  

Sachin Tendulkar

No comments:

Post a Comment