Append a character to end of a String in Java
This post will discuss how to append a character to the end of a string in Java.
1. Using String concat (+)
A simple solution to append a character to the end of a string is using the string concatenation operator (+). This creates a new instance of the string, since strings in Java are immutable and cannot be modified.
|
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { String str = "C"; char ch = '#'; str = str + ch; System.out.println(str); // C# } } |
Alternatively, you can use the += operator, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { String str = "C"; char ch = '#'; str += ch; System.out.println(str); // C# } } |
2. Using StringBuilder
Another plausible way of appending a character to the end of a string is using StringBuilder. The idea is to convert the string to a StringBuilder and call its append() method to append a character. Finally, convert the StringBuilder back to a string.
Note, you should prefer StringBuilder over StringBuffer since it’s not synchronized and faster. Here’s how the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { String str = "C"; char ch = '+'; str = new StringBuilder(str).append(ch).append(ch).toString(); System.out.println(str); // C++ } } |
3. Using String.format() method
Finally, you can use the String.format() method that returns a formatted string from the specified format specifiers. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 |
public class Main { public static void main(String[] args) { String str = "C"; char ch = '#'; str = String.format("%s%c", str, ch); System.out.println(str); // C# } } |
That’s all about appending a character to the end of a string in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)