avatarMalvin Lok

Summary

This article discusses eight ways to concatenate strings in Java, including using the "+" operator, StringBuilder or StringBuffer class, StringJoiner class, join method from the String class, StringUtils class, concat method from the String class, formatting a String with the String.format() method, and implementing with Stream.

Abstract

The article "8 Ways to Splice Common Strings in Java, There Is Always One You Like!" provides a comprehensive overview of various methods to concatenate strings in Java. The first method discussed is using the "+" operator, which is simple but can create performance issues due to the creation of new String objects. The StringBuilder and StringBuffer classes are introduced as alternatives that avoid this issue. The StringJoiner class is presented as a newer way to concatenate strings, offering a more concise approach. The join method from the String class is also discussed, which joins elements of an array or other iterable objects into a single string. The article also mentions the StringUtils class, a string tool class method in the Apache Commons Lang library, and the concat method from the String class. The String.format() method is introduced as a tricky but viable way to concatenate strings. Lastly, the article discusses implementing string concatenation with Stream, which is similar to the String.join() method but uses different syntax.

Opinions

  • The "+" operator method is simple and easy to understand but can lead to performance issues.
  • StringBuilder and StringBuffer classes are recommended for better performance in string concatenation.
  • The StringJoiner class offers a more concise way to concatenate strings.
  • The join method from the String class is useful for joining elements of an array or other iterable objects into a single string.
  • The StringUtils class is a valuable tool for string manipulation in the Apache Commons Lang library.
  • The concat method from the String class is straightforward but can throw a NullPointerException if the concatenated string is null.
  • The String.format() method is a tricky but viable way to concatenate strings.
  • Implementing string concatenation with Stream is similar to the String.join() method but uses different syntax.

8 Ways to Splice Common Strings in Java, There Is Always One You Like!

Photo by Blake Wisz on Unsplash

In Java programming, string splicing is a very basic operation, which involves many common scenarios in daily development work, such as splicing SQL statements, constructing HTTP request parameters, and so on.

Therefore, a good grasp of string splicing techniques not only helps to improve code efficiency but also to avoid some potential performance problems.

Below we will list out a few ways, with examples!

1. String concatenation using the “+” operator

This is the most common form of string concatenation, where multiple strings can be concatenated using the + operator, for example:

String str1 = "Hello";
String str2 = "World!";
String result = str1 + " " + str2;
System.out.println(result); 
//Hello World!

Pros: The code is simple to write and easy to understand and maintain.

Cons: Performance problem: every time you use the “+” operator to concatenate strings, a new String object will be created.

2. Using StringBuilder or StringBuffer Class

Both the StringBuilder and StringBuffer classes provide the append() method for concatenating strings. For example:

StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Hello");
stringBuilder.append(" ");
stringBuilder.append("World!");
System.out.println(stringBuilder.toString();); 
//Hello World!

StringBuffer stringBuffer2 = new StringBuffer();
stringBuffer2.append("Hello").append(" ").append("World");
System.out.println(stringBuffer2.toString()); 
//Hello World!

Using these two classes avoids creating a large number of string objects, which improves performance.

3. Using the StringJoiner class

StringJoiner is a relatively new way of string splicing. Through this class, you can more concisely realize the string splicing.

The StringJoiner class provides 2 constructors:

  1. StringJoiner(CharSequence delimiter): create a StringJoiner object with the specified delimiter.
  2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): use the specified delimiter, prefix and suffix to create a StringJoiner object.

Then add elements to the StringJoiner object through the add() method, and finally call the toString() method to get the spliced string.

Example:

StringJoiner stringJoiner = new StringJoiner(",");
stringJoiner.add("one");
stringJoiner.add("two");
stringJoiner.add("three");
System.out.println(stringJoiner.toString()); 
//one, two, three

StringJoiner stringJoiner2 = new StringJoiner(",","(",")");
stringJoiner2.add("one");
stringJoiner2.add("two");
stringJoiner2.add("three");
System.out.println(stringJoiner2.toString()); 
//(one, two, three)

4. Using the join method from the String class

The String.join() method is used to concatenate strings.

This method joins elements of an array of strings or other iterable objects into a single string and separates them using the specified separator.

Example:

String[] arr = {"one", "two", "three"};
List<String> lst = Arrays.asList("one", "two", "three")
String result = String.join(", ", arr);
System.out.println(result); 
//one, two, three
String result2 = String.join("#", lst);
System.out.println(result2);
//one#two#three

5. Using the StringUtils class

StringUtils.join() method is a string tool class method in the Apache Commons Lang library, there are many methods overloaded here that will not be shown, and do not pass the separator default.

Used to splice multiple strings into one string. For example:

String[] arr = {"Hello", "World"};
String str = StringUtils.join(Arrays.asList(arr), ' ');
System.out.println(str);
//Hello World

6. Using the concat method from the String class

The String.concat() method is used to concatenate one or more strings to form a new string. For example:

String str1 = "Hello";
String str2 = "world";
String result = str1.concat(" ").concat(str2);
System.out.println(result);  
//Hello world

If the concatenated string is null, concat() throws a NullPointerException.

7. Formatting a String with the String.format() method

This is very tricky, but still, a way to splice the string together.

String str = String.format("%s %s", "Hello", "World");
System.out.println(str);  
//Hello world

8. Implementing with Stream

This is very alike String.join(), but switches to another syntax。

List<String> lst = Arrays.asList("Hello", "World");
String str = lst.stream().collect(Collectors.joining(" "));
System.out.println(str);  
//Hello world

String splicing is a very common operation in Java.

Different scenarios require choosing the right string splicing method to achieve higher efficiency and better code readability.

Thanks for watching. See you.

Java
Java8
Code
Code Newbie
Tips
Recommended from ReadMedium