java

How to add a character to a string in Java

In this tutorial, we are going to see how to add a character at the begining, middle, and end of a string in Java.

  • By using the concatenation operator +
  • By using the StringBuffer constructor

 

Add a character to a string by using the concatenation operator +:
import java.util.*;

public class Main {
    public static void main(String[] args) {
    
        char c = 'o';         
        String str = "StackHowT"; 
        // add the character at the end of the string
        str = str + c;      
        // Display the result
        System.out.println(str); 
		
        c = 'S'; 
        str = "tackHowTo"; 
        // add the character at the begining of the string
        str = c + str;
        // Display the result
        System.out.println(str);
    }
}

Output:

StackHowTo
StackHowTo
 

Add a character to a string by using the StringBuffer constructor:

Using StringBuffer, we can insert characters at the begining, middle, and end of a string.

import java.util.*;

public class Main {
    public static void main(String[] args) {
    
        char c = 'o';  
        StringBuffer str = new StringBuffer("StackHowT"); 
        // add the character at the end of the string
        str.append(c);    
        // Display the result
        System.out.println(str); 
		
        str = new StringBuffer("tackHowTo"); 
        // add the character at the begining of the string
        str.insert(0,'S');       
        System.out.println(str); 
		
        str = new StringBuffer("StackowTo"); 
        // add the character 'L' in the middle of the string
        str.insert(5,'H');       
        System.out.println(str);
    }
}

Output:

StackHowTo
StackHowTo
StackHowTo
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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