How to add a Char to a String in Java
In most programming languages, a string is just an array of characters.
A character is a data type that can hold a single value.
Java offers many different ways in which you can extend a string with a new character.
In this post, we'll explore the many different ways in which you can add a character to a string.
Using the + operator
The most straightforward way to add a character to a string is to use the + operator.
This operator is used to concatenate two strings together, but it can also be used to add a character to a string.
JAVApublic class Example {
public static void main(String[] args) {
char charToAdd = 'A';
String str = "Hello world " + charToAdd;
System.out.println(str);
}
}
BASHHello world A
What happens under the hood is that the character is converted to a string automatically and then concatenated to the string.
Using the append() method on the StringBuilder class
Another way you can add a character to a string is to use the append()
method on the StringBuilder class.
The StringBuilder class, as its name suggests, helps you build a string piece by piece.
One of those pieces can be your character.
Here's our earlier example but using the StringBuilder class:
JAVApublic class Example {
public static void main(String[] args) {
char charToAdd = 'A';
StringBuilder str = new StringBuilder("Hello world ");
str.append(charToAdd);
System.out.println(str);
}
}
BASHHello world A
The append()
method can in take in a character, which it will convert to a string and then add it to the sequence internally.
Conclusion
In this post, we looked at the two different ways in which you can add a character to a string.
They work essentially the same way, but the StringBuilder class is more efficient if you're using it to build a complex string.
Hopefully, this post has helped you. Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Getting Started with Moon.js