EN
Java - add character to string
0 points
In this article, we would like to show you how to add character to string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABC";
2
char character = 'x';
3
String result = text + character;
4
5
System.out.println(result); // ABCx
In this example, we add character
at the end of the text
String using +
operator.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC";
5
char character = 'x';
6
String result = text + character;
7
8
System.out.println(result); // ABCx
9
}
10
}
Output:
xxxxxxxxxx
1
ABCx
In this example, we present how to add a character
in the middle of the text
String using substring()
method.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC";
5
char character = 'x';
6
String result = text.substring(0,1) + character + text.substring(1);
7
8
System.out.println(result); // AxBC
9
}
10
}
Output:
xxxxxxxxxx
1
AxBC
In this exmaple, we create a StringBuilder
object and add both the char
and the String
to it using append()
method.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABC";
5
char character = 'x';
6
7
// create StringBuilder object
8
StringBuilder stringBuilder1 = new StringBuilder();
9
10
// Add text and character to the StringBuilder object
11
stringBuilder1.append(text).append(character);
12
13
System.out.println(stringBuilder1); // ABCx
14
}
15
}
Output:
xxxxxxxxxx
1
AxBC