0% found this document useful (0 votes)
3 views10 pages

Java String Concatenation Methods

Uploaded by

tesla77806
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views10 pages

Java String Concatenation Methods

Uploaded by

tesla77806
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

String Concatenation in

Java
String Concatenation

 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
String Concatenation by + operator

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


String Concatenation by + operator : Example 1

class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
[Link](s);
}
}
Output: Sachin Tendulkar
String Concatenation by + operator

The Java compiler transforms above code to this:

String s=(new StringBuilder()).append("Sachin").append(" Tendulkar”).toString();


String Concatenation by + operator

 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.
String Concatenation by + operator: Example 2

class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
[Link](s);
}
}
Output: 80Sachin4040
String Concatenation by + operator

After a string literal, all the + will be treated as string concatenation operator.
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)


String Concatenation by concat() method: Example

class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=[Link](s2);
System. out. println(s3);
}
}
Output: Sachin Tendulkar

You might also like