String concatenation means creating a new string by combining the multiple strings. Using the Java string concat() method you can concatenate multiple strings. This is not the only way to do it, but you can also use the “+ ” operator, StringBuilder, StringBuffer, etc. In this tutorial, you will learn how to do Java String concatenation in different ways.
Java String concatenation Ways
Here are 3 ways to concat string in java programming:
- Using concat() method
- Using + (string concatenation) operator
- StringBuilder
Java string concat examples
Let’s see the examples of it, in different ways.
1. Using Java String concat | Method
Java String concat() method append a string to another string. This means this method concatenates one string to the end of another string.
Syntax this method:-
public String concat(String str)
Return– methods return a string.
See example code, we have
public class Hello { public static void main(String args[]) { String str1 = "Hello "; String str2 = "World !"; String str3 = str1.concat(str2); System.out.println(str3); } }
Output: Hello World !
2. String concatenation in java using + operator
Concatenate two strings in java using the + operator is too easy. We can call it a string concatenation operator. It produces a new string appending the second operand onto the end of the first operand and so on if more than 2.
+ operator not adding only string type values. You can concat integer values also (primitive values). See below simple example.
public class Hello { public static void main(String args[]) { String str = 007 + "EyeHunts" + 1 + 1; System.out.println(str); } }
Output: 7EyeHunts11
3. Using StringBuilder for string concatenation
By using StringBuilder’s append method you can add multiple strings. See below line of code.
StringBuilder sb = new StringBuilder(); str = sb.append(str1).append(str2).append(str3).toString();
Q: How to do string concatenation in java using for loop?
Answer: Java concat strings using for-loop? Seriously? Why do
Obviously, it’s not your choice if there are a method and operator available to do Java – Add two strings. But interviewers can ask this tricky question.
String
is immutable:
//Inefficient version using immutable String String output = "Some text"; int count = 100; for (int i = 0; i < count; i++) { output += i; } return output;
StringBuffer
is mutable:
//More efficient version using mutable StringBuffer StringBuffer output = new StringBuffer(110); output.append("Some text"); for (int i = 0; i < count; i++) { output.append(i); } return output.toString();
These are the best way to concatenate strings in java, do comment if you have any doubt and another way to do it.
Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java String concat Method Examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.