6 ways to Concatenate Strings in Java (Bonus: Choose concatenation character)
Let's try to understand what are our options:
1. Using the '+' operator
This is the easiest and the most commonly used option. We can simply use '+' between 2 Strings to concatenate them.
String s1 = "Hello"; String s2 = "World"; System.out.println(s1+s2);
Output:
HelloWorld
2. Using concat() function
Java has inbuilt function for concatenation. + operator is used for addition operations as well. If you want your code to be specific and readable, concat() function is an easy approach.
String s1 = "Hello"; String s2 = "World"; System.out.println(s1.concat(s2));
Output:
HelloWorld
3. Using StringBuilder class
StringBuilder class has inbuilt methond append(), which we can use for concatenation operation.
StringBuilder sb1 = new StringBuilder("String"); StringBuilder sb2 = new StringBuilder("Builder"); System.out.println(sb1.append(sb2));
Output:
StringBuilder
4. Using String format() method
String format is a functionality, which we can utilize to concatenate Strings.
String s1 = "Hello"; String s2 = "World";
System.out.println(String.format("%s%s", s1,s2));
Output:
HelloWorld
5. Using String join() method
String.join() function is another method which can be utilized for concatenation. Bonus part is, you can specify the concatenation character. So, if you want a space character between all your Strings, this method gives you that flexibility.
String s1 = "Hello"; String s2 = "World";
System.out.println(String.join(" ", s1,s2));
Output:
Hello World
6. Using StringJoiner class
We can utilize StringJoiner class to concatenate Strings. As with String.join() method, this class also adds a bonus functionality of choosing a concatenation operator.
import java.util.StringJoiner;
String s1 = "Hello"; String s2 = "World";
StringJoiner sj1 = new StringJoiner(","); sj1.add(s1); sj1.add(s2); System.out.println(sj1.toString());
Output:
Hello,World
Just to reiterate all the options we have, let's have a single piece of code for your reference, which includes all the above options:
import java.util.StringJoiner; public class ConcatString { public static void main(String[] args) { String s1 = "Hello"; String s2 = "World"; //Option 1 System.out.println(s1+s2); //Option 2 System.out.println(s1.concat(s2)); StringBuilder sb1 = new StringBuilder("String"); StringBuilder sb2 = new StringBuilder("Builder"); //Option 3 System.out.println(sb1.append(sb2)); //Option 4 System.out.println(String.format("%s%s", s1,s2)); //Option5 System.out.println(String.join(" ", s1,s2)); StringJoiner sj1 = new StringJoiner(","); sj1.add(s1); sj1.add(s2); //Option 6 System.out.println(sj1.toString()); } }
Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on Facebook, Twitter, Tumblr.
Comments
Post a Comment