Add character to String in java

In this post, we will see how to add character to String in java.

There are multiple ways to add character to String.

Add character to the start of String

You can add character at start of String using + operator.

Add character to the end of String

You can add character at start of String using + operator.

Further reading

How to compare characters in Java

Learn about how to compare characters in java using different methods ...

Java remove last character from string

Learn about how to remove last character from String in java using different ways ...

How to check if String has all unique characters in java

Learn about how to check if String has all unique characters in java ...

Here is the complete program to add character at start and end of the String.

Output:

Java2blog
Java2blog

As you can see, we have added 'J' to start of String "ava2blog" and added 'g' to the end of "Java2blo".

Add character to String at given postion

There are several methods to add Add character to String at given position.

Using StringBuffer

You can use StringBuffer's insert() method to add character to String at given position.
Let’s see with the help of an example.

Output:

Java2blog

As you can see, we have add char '2' at position 4 to String "Javablog".

In case, you want thread safe code, then you should use StringBuffer instead of StringBuilder.

Using substring

You can also use String’s substring method to add character to String at given position.
Let’s see with the help of an example.

Output:

Java2blog

Explanation

  • Get a substring before the positon
  • Add character
  • Get a substring after the positon

Although this looks easy and readable solution, there is disadvantage of using this approach.

As we already know String is immutable in java. Each substring call creates new String object.

When we use + operator to concatenate string, it internally creates StringBuffer objects as well.

If we need to call this method many times, then this may cause frequent garbage collection as heap memory will be filled faster due to temporary objects.

Using Apache common lang3

You can also use Apache common’s StringUtils to add character to the string at any postion
Here is the dependency which you need to add for Apache common lang3 in pom.xml.

Here is the example:

Output:

Java2blog

As you can see, we have used StringUtils‘s overlay() method to add character to the String at given position.
StringUtils.overlay(str, overlay, start, end) takes four arguments.
str: Orignal String
overlay: String which you want to add
start: start position
end: end position

Since we just want to add one character, start and end positions are the same pos.

Conclusion

We have seen multiple ways to add character to String at various positions.

That’s all about Add character to String in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *