Java Program to Add Characters to a String
Last Updated :
06 Sep, 2023
We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows:
Illustration:
Input:
Input custom string = Hello
Output:
--> String to be added 'Geeks'
--> If end position, Output: HelloGeeks
--> If in beginning, Output: GeeksHello
--> If at sat 3rd index, Output: HelGeekslo
Methods: This can be done using multiple methods of which frequently used methods are listed below as follows:
- Using + operator
- At the end
- At the beginning
- Using insert() method of StringBuffer class
- Using substring() method
Let us discuss all three methods above listed in detail to get a fair understanding of the same
Method 1: Using + operator
1.1 At the end
Example: One can add character at the start of String using the '+' operator.
Java
// Java Program to Add Characters to a String
// At the End
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Input character and string
char a = 's';
String str = "GeeksforGeek";
// Inserting at the end
String str2 = str + a;
// Print and display the above string
System.out.println(str2);
}
}
1.2 At the beginning
Example: One can add character at the start of String using the '+' operator.
Java
// Java Program to Add Characters to a String
// At the Beginning
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Input character and string
char a = 'G';
String str = "eeksforGeeks";
// Inserting at the beginning
String str2 = a + str;
// Print and display the above string
System.out.println(str2);
}
}
Method 2: Using insert() method of StringBuffer class
StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents grow able and writable character sequences. StringBuffer may have characters and sub-strings inserted in the middle or appended to the end. It will automatically grow to make room for such additions and often has more characters pre-allocated than are actually needed, to allow room for growth. One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer.
Syntax:
str.insert(int position, char x);
str.insert(int position, boolean x);
str.insert(int position, char[] x);
str.insert(int position, float x);
str.insert(int position, double x);
str.insert(int position, long x);
str.insert(int position, int x);
position is the index in string where
we need to insert.
Return type: A reference to this object.
Example
Java
// Java Program to Add Characters to a String
// Using StringBuffer class insert() method
// Main class
// AddCharacterToStringAnyPosition
public class GFG {
// Method 1
// To add character to string
public static String addCharToString(String str, char c,
int pos)
{
// Creating an object of StringBuffer class
StringBuffer stringBuffer = new StringBuffer(str);
// insert() method where position of character to be
// inserted is specified as in arguments
stringBuffer.insert(pos, c);
// Return the updated string
// Concatenated string
return stringBuffer.toString();
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Input string and character
String blogName = "GeeksforGeeks";
char two = 'f';
// Calling the method 1 to
// add character to a string
// Custom string, character and position passed
String cblogName
= addCharToString(blogName, two, 5);
// Print and display th above string
System.out.println(cblogName);
}
}
Method 3: Using substring() method
One can also use String’s substring method to add character to String at given position. This method has two variants, and it returns a new string that is substring of a string where the substring begins with a character at the specified index and extends to the end of the string.
Syntax:
public String substring(int begIndex)
Parameters: The beginning index, inclusive.
Return Value: The specified substring.
Example
Java
// Java Program to Add Characters to a String
// Using substring() method
// Main class
// AddCharacterToStringAnyPosition
public class GFG {
// Method 1
// To add character to a string
public static String
addCharToStringUsingSubString(String str, char c,
int pos)
{
return str.substring(0, pos) + c
+ str.substring(pos);
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Custom input character and string
String blogName = "GeeksforGeeks";
char two = 'f';
// Calling the Method 1 to
// To add character to a string
// Custom arguments
String cblogName = addCharToStringUsingSubString(
blogName, two, 5);
// Print and display the above string on console
System.out.println(cblogName);
}
}
Similar Reads
Java Program to Replace Multiple Characters in a String In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: Using String.replace() methodUsing replaceAll() method Using replaceFirst() method Method 1: Using String.replace() method This method returns a new st
3 min read
How to Convert a String to a Character in Java? String and char are fundamental and most commonly used datatypes in Java. A String is not a primitive data type like char. To convert a String to char in Java, we have to perform character-based operations or have to process individual characters.In this article, we will learn how to convert a Strin
3 min read
Java Program to Separate the Individual Characters from a String The string is a sequence of characters including spaces. Objects of String are immutable in java, which means that once an object is created in a string, it's content cannot be changed. In this particular problem statement, we are given to separate each individual characters from the string provided
2 min read
Java Program to Shuffle Characters in a String Without Using Shuffle() Rearranging the order of characters, in a string can be done by shuffling them. Although the shuffle() method provided by Java's Collections class is handy there are situations where you might require approaches. In this article, we will explore techniques, for shuffling characters in a string witho
3 min read
Remove first and last character of a string in Java Given a string str, the task is to write the Java Program to remove the first and the last character of the string and print the modified string.Examples:Input: str = "GeeksForGeeks"Output: "eeksForGeek"Explanation: The first and last characters of the given string are 'G' and 's' respectively. Afte
4 min read
How to find the first and last character of a string in Java Given a string str, the task is to print the first and the last character of the string. Examples: Input: str = "GeeksForGeeks" Output: First: G Last: s Explanation: The first character of the given string is 'G' and the last character of given string is 's'. Input: str = "Java" Output: First: J Las
3 min read
Convert a String to Character Array in Java Converting a string to a character array is a common operation in Java. We convert string to char array in Java mostly for string manipulation, iteration, or other processing of characters. In this article, we will learn various ways to convert a string into a character array in Java with examples.E
2 min read
Convert String to Stream of Chars in Java The StringReader class from the java.io package in Java can be used to convert a String to a character stream. When you need to read characters from a string as though it were an input stream, the StringReader class can be helpful in creating a character stream from a string. In this article, we wil
2 min read
Iterate Over the Characters of a String in Java Given string str of length N, the task is to traverse the string and print all the characters of the given string. Illustration: Input : âGeeksforGeeksâ Output : G e e k s f o r G e e k sInput. : âCoderâ Output : C o d e r Methods: Using Naive ApproachUsing String.toCharArray() methodUsing Character
9 min read
How to Shuffle Characters in a String in Java? In this article, we will learn how to shuffle characters in a String by using Java programming. For this, we have taken a String value as input and the method is available in java.util package and this method takes a list as input. Steps to shuffle characters in a String in JavaFirst, take one Strin
2 min read