Java - Core Java - String Handling

String Handling

String is a sequence of characters places in double quotes (“ ”). Performing different operations on strings is called string handling. In java, objects of String are immutable which means a constant and cannot be changed in the same memory after they are created. Hance String is defined as immutable sequence of characters.

In Java we have following three class to store and perform operations on strings.

  • String
  • StringBuffer
  • StringBuilder
  • StringBuilder was introduced as a non thread safe class. All these three classes are subclasses of CharSequence interface.

    All these three classes are final classes and subclasses of interface

    Any data enclosed in “ ” is treated by compiler and as an instance of java.lang.String

        String         s1 = ”abc”;  (valid)
        StringBuffer     s1 = ”abc”;  (invalid)
        StringBuilder    s1 = ”abc”;  (invalid)


    There are two ways to create string in Java:

    String literal
    String s = “JavaProgramming”;
    Using new keyword
    String s = new String (“JavaProgramming”);

    WAP to perform all string operations

    import java.util.*;
    class StringOperation
        public static void main(String[] args)
            String first="",second="";
            Scanner sc=new Scanner(;
                System.out.println("String Operation");
                System.out.print("Enter the first Sting: ");
            System.out.print("Enter the second Sting: ");
                System.out.println("The strings are: "+first+" , "+second);
             System.out.println("The length of the first string is :"+first.length());
                    System.out.println("The length of the second string is :"+second.length());
                System.out.println("The concatenation of first and second string is :"+first.concat(" "+second));
                 System.out.println("The first character of " +first+" is: "+first.charAt(0));
                System.out.println("The uppercase of " +first+" is: "+first.toUpperCase());
                System.out.println("The lowercase of " +first+" is: "+first.toLowerCase());
                System.out.print("Enter the occurance of a character in "+first+" : ");
                 char c=str.charAt(0);
                System.out.println("The "+c+" occurs at position " + first.indexOf(c)+ " in " + first);
                 System.out.println("The substring of "+first+" starting from index 3 and ending at 6 is: " + first.substring(3,7));
                System.out.println("Replacing 'a' with 'o' in "+first+" is: "+first.replace('a','o'));        
                boolean check=first.equals(second);
                    System.out.println(first + " and " + second + " are not same.");
                    System.out.println(first + " and " + second + " are same.");  
    String is immutable for several reasons:
    Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed. Synchronization and Concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues. Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object). Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).


    It is a thread safe mutable sequence of characters. It is like a String but can be modified in the same memory location.

    Program to uses of constructor and methods

    class Demo{
    public static void main(String args[])
       StringBuffer sb1 = new StringBuffer();
       System.out.println("sb1 length: " + sb1.length());      // prints 0 as there is not data in the buffer
       System.out.println("sb1 capacity: " + sb1.capacity());  // prints 16, the default capacity
       StringBuffer sb2 = new StringBuffer(50);
       System.out.println("sb2 length: " + sb2.length());      // prints 0 as there is not data in the buffer
       System.out.println("sb2 capacity: " + sb2.capacity());  // prints 50
       String str1 = "hello";
       StringBuffer sb3 = new StringBuffer(str1);
       System.out.println("sb3 length: " + sb3.length());      // prints 5, the length of hello
       System.out.println("sb3 capacity: " + sb3.capacity());  // prints 22; str1.length()+16
       CharSequence seq1 = "hello";
       StringBuffer sb4 = new StringBuffer(seq1);
       System.out.println("sb4 length: " + sb4.length());      // prints 5, the length of hello
       System.out.println("sb4 capacity: " + sb4.capacity());  // prints 22; str1.length()+16


    It is same as StringBuffer and the constructors are also same as StringBuffer.

    Program to use of StringBuilder
    import java.lang.StringBuilder;
    public class Program {
        public static void main(String[] args) {
            // Create a new StringBuilder.
            StringBuilder builder = new StringBuilder();
            // Loop and append values.
            for (int i = 0; i < 5; i++) {
                builder.append("abc ");
            // Convert to string.
            String result = builder.toString();
            // Print result.
    When should we go for String, StringBuffer and StringBuilder?
  • If we don’t want to store string modification in same memory, must use String
  • If we want to store modification in same memory, must use StringBuffer or StringBuilder
  • What are the different ways for converting String to StringBuffer or StringBuffer to String?
  • We can convert String to StringBuffer using StringBuffer(String) constructor