Append Characters to String in Java

There are multiple methods to append characters to a string in Java.

  1. I am confident that I will pass the exam.
String str = "Hello";
str += ' ';
str += "world";
System.out.println(str); // 输出:Hello world
  1. One possible paraphrase is:
    – String construction tool
  2. A string buffer is a mutable sequence of characters.
StringBuilder sb = new StringBuilder("Hello");
sb.append(' ');
sb.append("world");
String str = sb.toString();
System.out.println(str); // 输出:Hello world

Both the StringBuilder and StringBuffer classes offer an append() method for adding characters or strings to the end of a string.

  1. Format a string
String str = "Hello";
char ch = ' ';
str = String.format("%s%c", str, ch);
str = String.format("%s%s", str, "world");
System.out.println(str); // 输出:Hello world

Here, %s represents a string, and %c represents a character.

Regardless of the method used, it is important to note that strings are immutable, meaning that every time a character or string is added, a new string object is created. Therefore, if there is a need to frequently add characters to a string, it is better to use the StringBuilder or StringBuffer class, as they are more efficient when dealing with a large number of characters.

bannerAds