Java String Insert Character at Specific Index

Java String insert a character at a specific index example shows how to insert a character in the string a specified index using the substring method.

How to insert a character into the string at a specific index?

The String class in Java does not provide any methods using which we can insert a character into it. The reason being is that the String is immutable in Java. In other words, it can not be changed once it is created.

But that does not mean that we can not do that. We can certainly insert a character in a string using the substring method and get a new string object having a new character sequence.

The String class provides two overloaded versions of the substring method.

This method returns a substring of the string starting from the start index till the last index.

This method returns the substring from a string starting at the startIndex and ending at the endIndex – 1.

We are going to use both of these methods to insert the character in the string as given below.

Output

As you can see from the code, we took string substring from index 0 to 4 (end index is exclusive), concatenated it with the character we want to insert, and concatenated it again with the string substring from index 5 till the end of the string.

The newer Java runtimes automatically optimize the string concatenation to use the StringBuilder. Though it happens automatically, you can still insert a character in the string at a specified index using the StringBuilder as given below.

Output

If you want to learn more about string in Java, please visit the Java String Tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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