How to add characters to a string in Java?

By Preeti Jain Last updated : January 31, 2024

To add characters to a string, there are two approaches - the first approach is to concatenate characters (strings) using the plus (+) operator and the second approach is to use StringBuffer.insert() method.

Add characters to string using concatenating

You can use the plus operator (+) directly to add characters (strings) to a string.

Example

public class AddCharactersToString {

  public static void main(String[] args) {
    String old_string = "Hello , Welcome in Java Worl";
    char added_char = 'd';
    String added_string = "d in version 8";

    old_string = old_string + added_char;
    String old_string1 = old_string + added_string;

    System.out.println(old_string);
    System.out.println(old_string1);
  }

}

Output

Output:
D:\Programs>javac AddCharactersToString.java

D:\Programs>java AddCharactersToString
Hello , Welcome in Java World
Hello , Welcome in Java Worldd in version 8

Add characters to string using StringBuffer.insert() method

You can also use the insert() method of StringBuffer class by specifying the offset and characters to be added.

Example

import java.lang.StringBuffer;

public class AddCharactersToString {
  public static void main(String[] args) {

    StringBuffer sb = new StringBuffer("Java is a programming language : ");

    // use insert(int offset ,Boolean b) 
    // it will insert the Boolean parameter at index 33 
    // as string to the StringBuffer
    sb.insert(33, true);

    // Display result after inserting
    System.out.println("The result will be after inserting Boolean object to the StringBuffer is :" + sb.toString());

    sb = new StringBuffer("Is java support OOPS : ");

    // use insert(int offset , int i) 
    // it will insert the String parameter at index 21 
    // as string to the StringBuffer
    sb.insert(21, "Yes");

    // Display result after inserting
    System.out.println("The result will be after inserting Integer object to the StringBuffer is :" + sb.toString());
  }
}

Output

D:\Programs>javac AddCharactersToString .java

D:\Programs>java AddCharactersToString
The result will be after inserting Boolean object to the StringBuffer is :Java is a programming language : true
The result will be after inserting Integer object to the StringBuffer is :Is Java Support OOPS : Yes

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.