Java add character to string java

How to Add char to String in Java

char” is a primitive data type belonging to the Java wrapper class “Character” that stores 16-bit Unicode characters. Java uses the char data type to store one character that is enclosed in single quotes (‘ ‘), While a “String” is used to hold a group of characters that are arranged in a particular order surrounded by double quotes (” “). Java provides multiple options for adding a new character to a String.

This blog will discuss the procedure of adding char to a String in Java.

Читайте также:  Скилл бокс питон разработчик

How to Add Char to String in Java?

For adding a character “char” to a String, you can use:

  • Concatenation Operator “+
  • substring() method
  • append() method
  • insert() method

Let’s have a look at these methods one by one!

Method 1: Add char to String Using Concatenation Operator “+”

The easiest and most commonly used method to add char to a String is the Concatenation operator “+”. It concatenates the character to a String. You can add additional characters either at the start, middle, or at the end of the String with the help of the “+” operator.

Syntax
The following syntax can be utilized to add char “ch” to a String “str”:

Example 1: Add char at the Start of the String
In this example, we will add the character “H” at the start of a String. To do so, we will create a char named “ch” with the specified values:

Next, we will concatenate the created char with the substring “ello” and store the resultant value in the “s” String:

Finally, we will print the value of our String:

The output shows that the character “H” is now concatenated with the “ello” substring, and the resultant String is “Hello”:

Example 2: Add char at the Middle of the String
Here, we will add a character “n” in the middle of the String:

Now, we will add the value of the created characters in between the “Li” and “ux” substrings, with the help of the “+” operator:

Then, simply print the value of “s” using the “System.out.println()” method:

As you can see, we have successfully added the specified char in the middle:

Example 3: Add char at the End of the String
Now, we will check how to add a character at the end of the String. We will have a character type variable “ch” that stores a character “t”:

Here, we have a String “Linux Hin”, which will be concatenated with the “ch” character and store the resultant value in “s” String:

At last, print the value of String type variable “s” on the console:

Let’s check other methods for adding char to the String in Java.

Method 2: Add char to String Using substring() Method

In Java, another method for adding a character to a String is the “substring()” method. It belongs to the String class.

Syntax
Here is the syntax of the “substring()” method for the specified purpose:

Call the substring() method with a String “s” and split it by passing the start index as a “firstIndex” and the index where you want to add the character as “secondIndex”. Now, add the character using the “+” operator and then concatenate the other part of the String starting from the passed “secondIndex”.

Example
We will add character “n” at the middle of the String using the “substring()” method:

The String “LiuxHint” is stored in the String type variable “s”. We want to add the character “n” before the character “u” that is placed at the “2” index:

We will split the String from the start to the 2nd index of the String “s” using “s.substring(0,2)” and add the character “ch” at that place, and then concatenate the remaining part of the String with “s.substring(2)” the start index of that and save it in a String type variable “sb”:

Finally, print the value of “sb” on the console window:

The output signifies that the “n” character is added to the “LiuxHint” String, and it becomes “LinuxHint”:

There are some other methods for adding characters to a String. Let’s move towards them.

Method 3: Add char to String Using append() Method

The “append()” method of the “StringBuilder” class is also used to add a character to a String in Java. In the StringBuilder class, you can build a String with concatenation. It works the same as the “+” operator.

Syntax
Follow the below syntax for using the “append()” method:

The append() method will be called with the object of the StringBuilder class “sb”, and it takes a character “ch” as an argument.

In this example, we will add the character “t” at the end of the String “LinuxHin” by utilizing the “append()” method:

The String “LinuxHin” will store in a String type variable “s”:

We will create an object “sb” of the “StringBuilder” class:

Now, we will call the “append()” method with object “sb” by passing it in a String “s” and then again call “append()” method and pass character “ch” as an argument:

Finally, we will print the object “sb” that contains the resultant String by adding a character in it:

The output shows that we have successfully added the character “t” at the end of the “LinuxHin” substring:

There is one more method for adding characters in between the Strings. Let’s check it out.

Method 4: Add char to String Using insert() Method

The “insert()” method of the “StringBuffer” class is also used to add characters in a String in Java. It adds the character at the specified position, similar to the substring() method. The characters and substrings can also be placed in the middle or appended at the end of a StringBuffer.

Syntax
The “insert()” method has the following syntax:

The insert() method is called with the object of the StringBuffer class “sb” by passing an “index” where you want to add the “ch” character.

Example
In this example, we will add the character “u” at the 3rd index of the String “LinxHint”. For this purpose, we have created a “ch” character:

The String “LinxHint” is stored in the “s” variable:

Then, we will create an object “sb” of the StringBuffer class and pass the created String as an argument to it:

Call the “insert()” method and pass character “ch” and the index as “3”:

Lastly, we will print the value of object “sb” with the help of the “System.out.println()” method:

The output shows that the character “u” is successfully added in the String “LinuxHint” at the 3rd index:

We have compiled all the methods related to adding a character to a String in Java.

Conclusion

For adding characters to a String, you can use the Concatenation Operator “+”, substring(), append(), and insert() method. The most common and easiest way to add character to a String. You can also add character at any place at either the String’s start, end, or middle by utilizing the “+” operator and the append() method. While for other methods, you have to mention the index. In this blog, we have discussed the methods for adding a character to a String in Java with detailed examples.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Add Char to String in Java

Add Char to String in Java

  1. Java Add Char to String Using + Operator
  2. Java Add Char to String Using StringBuilder.append()
  3. Java Add Char to a String Using the substring() Method

This article will introduce how we can add a character to a string in Java. A character in Java is represented by the data type char , and it holds only a single value. We will use several methods to add char to string Java at different positions.

Java Add Char to String Using + Operator

This is the easiest and most straightforward way to add a character to a string in Java. We concatenate a char to the string using the + operator. In the program below, we have two char values — charToAdd1 and charToAdd2 which we will concatenate with strings — alex and bob .

In the first variable — alex , we have added charToAdd1 at the last position, while charToAdd2 is added in the middle. One thing to notice is that when we use the + concatenation, any data type like char will be converted to a string.

public class AddCharToString   public static void main(String[] args)   char charToAdd1 = 'A';  char charToAdd2 = 'C';   String alex = "Alex got Grade " + charToAdd1;  String bob = "While Bob got " + charToAdd2 + " Grade";   System.out.println(alex);  System.out.println(bob);   > > 
Alex got Grade A While Bob got C Grade 

Java Add Char to String Using StringBuilder.append()

In this method, we add char to string using the append() function of the StringBuilder class in Java. This function appends two or more strings just like the + operator.

In the below example, we create two StringBuilder objects and then first append the charToAdd1 to alex and then join charToAdd2 to bob .

public class AddChartToString   public static void main(String[] args)    char charToAdd1 = 'A';  char charToAdd2 = 'C';   StringBuilder stringBuilder1 = new StringBuilder();  StringBuilder stringBuilder2 = new StringBuilder();   String alex = "Alex got Grade ";  String bob = "While Bob got Grade ";   stringBuilder1.append(alex).append(charToAdd1);  stringBuilder2.append(bob).append(charToAdd2);   System.out.println(stringBuilder1);  System.out.println(stringBuilder2);   > > 
Alex got Grade A While Bob got Grade C 

Java Add Char to a String Using the substring() Method

This example uses the substring() method of the String class, which takes out a specified part of the string. In the code below, we can see that we first get the starting part of the alex by setting the position of the characters in the string. alex.substring(0, 15) takes the starting and the ending index.

Next, we will concatenate charToAdd1 using + , and at the end, we will join the remaining part of alex by alex.substring(15) , where we pass the starting index as an argument.

We are doing the same for bobResult as it has a typo, and we want to fix it by adding the character ( g ). We will use the same solution for this.

public class AddChartToString   public static void main(String[] args)    char charToAdd1 = 'A';  char charToAdd2 = 'g';   String alex = "Alex got Grade in the School";  String bob = "While Bob ot Grade C";   String alexResult = alex.substring(0, 15) + charToAdd1 +alex.substring(15);  String bobResult = bob.substring(0, 10) + charToAdd2 + bob.substring(10);  System.out.println(alexResult);  System.out.println(bobResult);   > > 
Alex got Grade A in the School While Bob got Grade C 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java Char

Related Article — Java String

Copyright © 2023. All right reserved

Источник

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

Java remove last character from string

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.

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.

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.

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 .

Источник

Оцените статью