String concate():
You can combine two strings by using concate() method in Java. Let’s check out some examples to understand concate()
method in Java.
Method signature:
The signature for a concate() method is as shown below.
public String concat(String str)
Method parameters and return type:
Parameters: It takes a string as a parameter.
Return type: It returns a combined string.
Throws: It throws NullPointerException if the string is null.
Example 1:
This example explains how you can combine two strings to make a complete statement. We have initialized the third string to store the result of the first two strings.
Source code:
public class Example1 {
public static void main(String argvs[]) {
String string1 = "I love ";
String string2 = "Java Programming";
String result= string1.concat(string2);
System.out.println(result);
}
}
Output:
run:
I love Java Programming
BUILD SUCCESSFUL (total time: 1 second)
Example 2:
In this example, we have used four strings. The fourth string is initialized with the concatenation of the second and third string. After that, we have compared the first and the fourth string. The program returned false because both strings are not equal.
Source code:
public class Example2 {
public static void main(String[] args) {
String str1= "I love Programming";
String str2="I love ";
String str3="Java Programming";
String str4=str2.concat(str3);
System.out.println("String 1 is: "+str1);
System.out.println("Concat of String 2 and String 3 is: "+str4);
if(str4.equals(str1)){
System.out.println("True");
} else{
System.out.println("False");
}
}
}
Output:
run:
String 1 is: I love Programming
Concat of String 2 and String 3 is: I love Java Programming
False
BUILD SUCCESSFUL (total time: 1 second)
Example 3:
You can also concatenate white spaces with the strings. In this example, we have explained how you can join a white space with a string.
Source code:
public class Example3 {
public static void main(String[] args) {
String str1="This is a Java tutorial";
String str2="At online tutorials point";
str1.concat(str2);
System.out.println(str1);
str1=str1.concat(" ").concat(str2);
System.out.println(str1);
}
}
Output:
run:
This is a Java tutorial
This is a Java tutorial At online tutorials point
BUILD SUCCESSFUL (total time: 0 seconds)
References:
Happy Learning:)