Languages
[Edit]
EN

Java - add character to string

0 points
Created by:
Abul-Emery
457

In this article, we would like to show you how to add character to string in Java.

Quick solution:

String text = "ABC";
char character = 'x';
String result = text + character;

System.out.println(result);  // ABCx

 

1. Practical example using + operator

In this example, we add character at the end of the text String using + operator.

public class Example {

    public static void main(String[] args) {
        String text = "ABC";
        char character = 'x';
        String result = text + character;

        System.out.println(result);  // ABCx
    }
}

Output:

ABCx

2. Practical example using String substring() method

In this example, we present how to add a character in the middle of the text String using substring() method.

public class Example {

    public static void main(String[] args) {
        String text = "ABC";
        char character = 'x';
        String result = text.substring(0,1) + character + text.substring(1);

        System.out.println(result);  // AxBC
    }
}

Output:

AxBC

3. Practical example using StringBuilder append() method

In this exmaple, we create a StringBuilder object and add both the char and the String to it using append() method.

public class Example {

    public static void main(String[] args) {
        String text = "ABC";
        char character = 'x';

        // create StringBuilder object
        StringBuilder stringBuilder1 = new StringBuilder();

        // Add text and character to the StringBuilder object
        stringBuilder1.append(text).append(character);

        System.out.println(stringBuilder1);  // ABCx
    }
}

Output:

AxBC
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join