Posted in

STRINGS PROGRAMS AND ALGORITHMS IN JAVA

1. Write a program to calculate the total number of characters in the String?

Algorithm :

  • Start
  • Initialize the String:
  • The string str is assigned the value “Scaler by InterviewBit”.
  •  Initialize Counter:
  •  An integer variable count is set to 0 to keep track of non-space characters.
  •  Print Input String:
  •  The program displays the input string using System.out.println.
  •  Loop Through the String:
  •  A for loop iterates from i = 0 to str.length() – 1:
    • Inside the loop, for each character, it checks if the character is not a space using str.charAt(i) != ‘ ‘.
    • If it’s not a space, count is incremented.
  • Print Result:
  • After the loop, the total count of non-space characters is printed.
  • End

Program :

      public class TotatCharacters
      {
    public static void main(String[] args)
    {   
       String str = “Scaler by InterviewBit”;   
       int count = 0;   
       System.out.println(“Input String: “+str);        
       for(int i = 0; i < str.length(); i++)
          {   
             if(str.charAt(i) != ‘ ‘)   
             count++;   
          }                 
       System.out.println(“The total number of characters in the given string: ” + count);   
    }     
}

Output :

Input String: Scaler by InterviewBit
The total number of characters in the given string: 20

Explanation :

           This Java program counts the total number of characters in a given string, excluding spaces. It initializes a counter and iterates through each character of the string using a loop. During each iteration, it checks if the character is not a space, and if so, increments the counter. Finally, it prints the total count of characters excluding spaces. For example, in the string “Scaler by InterviewBit”, the program correctly identifies and counts all characters except for the space between words.  

2. How to print all permutations of string in Java?

Algorithm :

  • Start in main():
  • The string s = “cat” is passed to the method printallPermutns(s, “”).
  •  Recursive Method printallPermutns(str, str2):
    • Base Case:
      If str is empty (str.length() == 0), it prints the value of str2, which is a complete permutation.
    • Recursive Case:
      For each character in str, do the following:
      • Extract the character at position i as ch.
      • Form a new string str3 by removing the i-th character from str.
      • Call the function recursively with str3 and str2 + ch.
  •  Execution Flow for “cat”:
  • First level: c, a, t
  • Second level (with remaining characters): combinations like a + t, t + a, etc.
  • Third level: final character added, completing the permutation.
  • All Recursive Calls eventually reach the base case, where the accumulated characters are printed as permutations.
  • End

Program :

  public class InterviewBit {
   static void printallPermutns(String str, String str2)
   {
       if (str.length() == 0)
         {
           System.out.print(str2 + ” “);
           return;
         }
       for (int i = 0; i < str.length(); i++)
         {
           char ch = str.charAt(i);
           String str3 = str.substring(0, i) + str.substring(i + 1);
           printallPermutns(str3, str2 + ch);
        }
   }
   public static void main(String[] args)
   {
       String s = “cat”;
       printallPermutns(s, “”);
   }
}

Output :

cat cta act atc tca tac

Explanation :

        This Java program recursively prints all permutations of a given string. It works by picking each character from the original string one at a time and appending it to an accumulating result (str2). The remaining characters (str3) are then passed recursively to form the next level of permutations. When the remaining string becomes empty, the complete permutation is printed. For example, for the input “cat”, it generates and prints all 6 possible permutations: cat, cta, act, atc, tca, and tac.

3. How to reverse a string in Java?

Algorithm :

  • Start in main():
  • Declare and initialize str = “Scaler by InterviewBit”.
  • Call the method revstr(str):
  • Inside this method:
    • A StringBuilder object is created with the string “Scaler by InterviewBit”.
    • The reverse() method is called on the StringBuilder, which reverses the characters.
    • The reversed string is converted back to a String using .toString() and returned.
  • Store and print the result:
    • The reversed string is stored back in str.
    • It prints: “Result after reversing a string is: tiBewweivretnI yb relacS”
  • End

Program :

public class ReverseString
     {
     public static String revstr(String str)
     {
          return new StringBuilder(str).reverse().toString();
     }
     public static void main(String[] args)
     {
         String str= “Scaler by InterviewBit”;
         str= revstr(str);
         System.out.println(“Result after reversing a string is: “+ str);
    }
}

Output :

Result after reversing a string is: tiBweivretnI yb relacS

Explanation :

The execution of the program begins in the main method where the string “Scaler by InterviewBit” is initialized. This string is then passed as an argument to the revstr method. Inside revstr, a StringBuilder object is created using the input string. The reverse() method of StringBuilder is called, which reverses the characters of the string. The reversed string is converted back to a String using toString() and returned to the caller. Finally, the reversed string is printed to the console with the message: “Result after reversing a string is: tiwevretnI yb relacS”.

4. Write a program to how can we remove a specific character from a String?

Algorithm :

  • Start in main():
    • Initialize str = “Scaler by InterviewBit”.
  • Remove all occurrences of character ‘e’:
    • Call str.replace(“e”, “”).
    • This removes every ‘e’ from the string.
    • Output: “Scalr by Int rviwBit”.
  • Remove the first occurrence of ‘e’:
    • Call str.replaceFirst(“e”, “”).
    • This removes only the first ‘e’.
    • Output: “Scalr by InterviewBit”.
  • Remove all uppercase letters:
    • Call str.replaceAll(“([A-Z])”, “”).
    • This uses a regex to match any uppercase letter ([A-Z]) and replaces it with an empty string.
    • Output: “caler by nterviewit”.
  • End

Program :

public class RemoveCharacter
{
  public static void main(String args[])
    {
      String str = “Scaler by InterviewBit”;  
      System.out.println(“String after removing ‘e’ = “+str.replace(“e”, “”));   
     System.out.println(“String after removing First ‘e’ = “+str.replaceFirst(“e”, “”));  
  System.out.println(“String after replacing all small letters = “+str.replaceAll(“([A-Z])”, “”));
  }
}

Output :

String after removing ‘e’ = Scalr by IntrviwBit
String after removing First ‘e’ = Scalr by InterviewBit
String after replacing all small letters = caler by nterviewit

Explanation :

This Java program demonstrates how to remove specific characters or patterns from a string using replace(), replaceFirst(), and replaceAll() methods. It starts with the string “Scaler by InterviewBit” and performs three operations: removing all ‘e’ characters, removing only the first ‘e’, and finally removing all uppercase letters using a regular expression. These methods help manipulate strings flexibly and are useful for text processing and cleaning tasks.

5. Write a program to check whether the given input string is a palindrome?

Algorithm :

  • Start in main() method:
    • Declare str1 = “rotator” (a known palindrome).
    • Call reverseString(str1) to get the reversed version.
  • Inside reverseString(str2) method:
    • Initialize revstr = “”.
    • Loop from the end of str2 to the beginning:
      • Append each character in reverse order to revstr.
      • After the loop, revstr = “rotator” (same as input).
    • Return revstr.
  • Back in main():
    • Compare str1 with revstr using .equals().
    • Since both are “rotator”, they are equal.
    • Print: “The string rotator is a Palindrome String.”
  • End

Program :

public class PalindromeChecker
{
    public static void main (String[] args)
    {
       String str1 = “rotator”;                        
       String revstr = reverseString(str1); //revstr=reverse string
       if (str1.equals(revstr))
          {
              System.out.println(“The string” + str1 + ” is a Palindrome String.”);
          }
        else
          {
           System.out.println(“The string” + str1 + ” is not a Palindrome String.”);
          }
    }
    public static String reverseString(String str2)
    {
        String revstr = “”;
        for (int i = str2.length() – 1; i >= 0; i–)
         {
            revstr += str2.charAt(i);
         }
            return revstr;
     }
}

Output :

The string rotator is a Palindrome String.

Explanation :

            This program checks whether a given string is a palindrome—a string that reads the same forwards and backwards. It reverses the string manually using a loop and then compares the reversed string with the original. If they match, it confirms that the string is a palindrome. In this example, the input “rotator” is identified correctly as a palindrome.

6. Write a program to count how many times a specific character appears in a string?

Algorithm :

  • Start
  • Input Initialization:
    • str = “hello world”
    • target = ‘o’
    • count = 0
  • Loop through the string:
    • For each character at index i from 0 to 10:
      • If str.charAt(i) is equal to ‘o’, increment count.
  • Character Comparison:
    • ‘o’ appears at index 4 and index 7.
    • So, count becomes 2.
  • Output:
    • The program prints:
      Character ‘o’ occurs 2 times.
  • End

Program :

     public class CountCharacter {
        public static void main(String[] args) {
          String str = “hello world”;
        char target = ‘o’;
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == target) {
                count++;
            }
        }
        System.out.println(“Character ‘” + target + “‘ occurs ” + count + ” times.”);
    }
}

Output :

Character ‘o’ occurs 2 times.

Explanation :

       This program counts how many times a specific character appears in a given string. It iterates through each character of the string using a loop and compares it with the target character. If a match is found, it increments a counter. Finally, it prints the total count. In this example, the character ‘o’ appears twice in the string “hello world”, so the output reflects that.

7. Write a program to find the first non-repeated character in a string?

Algorithm :

  • Start
  • Input:
    • str = “swiss”
  • Create a HashMap to store character counts.
  • First Loop – Count Characters:
    • s → count 1
    • w → count 1
    • i → count 1
    • s → count 2
    • s → count 3
      → Final map: {s=3, w=1, i=1}
  • Second Loop – Find First Non-Repeated Character:
    • Check each character in order:
      • s → count is 3 → skip
      • w → count is 1 → print and break
  • Output:
    • First non-repeated character: w
  • End

Program :

import java.util.HashMap;
    public class FirstNonRepeatedChar {
    public static void main(String[] args) {
        String str = “swiss”;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            map.put(str.charAt(i), map.getOrDefault(str.charAt(i), 0) + 1);
        }
        for (int i = 0; i < str.length(); i++) {
            if (map.get(str.charAt(i)) == 1) {
                System.out.println(“First non-repeated character: ” + str.charAt(i));
                break;
            }
        }
    }
}

Output :

First non-repeated character: w

Explanation :

        This program finds the first non-repeated character in a string. It first counts the frequency of each character using a HashMap, then iterates through the string again to find the first character that has a count of one. For the input “swiss”, the character ‘w’ is the first that does not repeat, so it is printed as the result.

8. Write a program to remove all white spaces from a string?

Algorithm :

  • Start
  •  Input String:
    • str = ” Hello World “
  • Replace All Whitespace:
    • str.replaceAll(“\\s+”, “”) uses a regular expression to remove:
      • All spaces
      • Tabs
      • New lines
  • In this case, all spaces (including multiple spaces) are removed.
  • Result:
    • result = “HelloWorld”
  • Print Output:
  • Output: String without spaces: “HelloWorld”
  • End

Program :

      public class RemoveSpaces {
           public static void main(String[] args) {
        String str = ”  Hello   World   “;
        String result = str.replaceAll(“\\s+”, “”); // Removes all whitespace
        System.out.println(“String without spaces: \”” + result + “\””);
    }
}

Output :

 String without spaces: “HelloWorld”

Explanation :

           The execution of the RemoveSpaces program starts in the main method where a string ” Hello World ” is defined with leading, trailing, and multiple spaces in between. The replaceAll method is then used with the regular expression \\s+, which matches one or more whitespace characters. This method replaces all such occurrences with an empty string, effectively removing all spaces from the original string. The resulting string, “HelloWorld”, is stored in the variable result. The program then prints the output: String without spaces: “HelloWorld”.

9. Write a program to count the number of words in a string?

Algorithm :

  • Start
  • Declare and initialize a string variable str with the sentence “Hello World from Java”.
  • Use the split() method with the regular expression “\\s+” to split the string into words based on whitespace.
  • Store the result in a string array called words.
  • Count the number of words by finding the length of the words array.
  • Display the word count using System.out.println.
  • End

Program :

public class WordCount {
       public static void main(String[] args) {
        String str = “Hello World from Java”;
        String[] words = str.split(“\\s+”); // Split by space
        System.out.println(“Number of words: ” + words.length);
    }
}

Output :

Number of words: 4

Explanation :

         The program counts the number of words in a string by splitting it using split(“\\s+”), which separates words by spaces. It then prints the length of the resulting array, which gives the total word count.

10. Write a program to check if two strings are anagrams (contain the same characters in any order)?

Algorithm :

  • Start
  •  Initialize two strings str1 = “listen” and str2 = “silent”.
  • Convert both strings to character arrays: arr1[] and arr2[].
  • Sort both character arrays using Arrays.sort().
  • Compare the sorted arrays using Arrays.equals().
  • If equal, print “The strings are anagrams.”
  • Else, print “The strings are not anagrams.”
  • End

Program :

import java.util.Arrays;
    public class AnagramCheck {
    public static void main(String[] args) {
        String str1 = “listen”;
        String str2 = “silent”;
        char[] arr1 = str1.toCharArray();
        char[] arr2 = str2.toCharArray();
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        if (Arrays.equals(arr1, arr2)) {
            System.out.println(“The strings are anagrams.”);
        } else {
            System.out.println(“The strings are not anagrams.”);
        }
    }
}

Output :

The strings are anagrams.

Explanation :

This program checks if two strings are anagrams (i.e., contain the same characters in different orders). It converts both strings into character arrays, sorts them, and compares them. If the sorted arrays are equal, the strings are anagrams.

11. Write a program to convert a string to an integer?

Algorithm :

  • Start
  • Declare a string variable str and assign it the value “12345”.
  • Use Integer.parseInt(str) to convert the string to an integer and store it in variable num.
  • Print the converted integer.
  • End

Program :

public class StringToInt {
         public static void main(String[] args) {
        String str = “12345”;
        int num = Integer.parseInt(str);
        System.out.println(“Converted number: ” + num);
    }
}

Output :

Converted number: 12345

Explanation :

This program converts a numeric string “12345” into an integer using Java’s built-in Integer.parseInt() method and prints the result.

12. Write a program to find the index of the first occurrence of a character in a string?

Algorithm :

  • Start
  • Declare a string str with value “Hello World”.
  • Define a target character target = ‘o’.
  • Use str.indexOf(target) to find the index of the first occurrence of ‘o’.
  • Store the result in index.
  • Print the index.
  • End

Program :

public class FirstIndexOfChar {
        public static void main(String[] args) {
        String str = “Hello World”;
        char target = ‘o’;
        int index = str.indexOf(target);
        System.out.println(“First occurrence of ‘” + target + “‘ is at index: ” + index);
    }
}

Output :

First occurrence of ‘o’ is at index: 4

Explanation :

This program finds the first occurrence of the character ‘o’ in the string “Hello World” using the indexOf() method and prints its position.

13. Write a program to convert a string to uppercase and lowercase?

Algorithm :

  • Start
  • Define a string str = “Java Programming”.
  • Convert str to uppercase using str.toUpperCase() and store it in upper.
  • Print upper.
  • Convert str to lowercase using str.toLowerCase() and store it in lower.
  • Print lower.
  • End

Program :

public class StringCaseConversion {
    public static void main(String[] args) {
        String str = “Java Programming”;     
        String upper = str.toUpperCase();
        System.out.println(“Uppercase: ” + upper);
        String lower = str.toLowerCase();
        System.out.println(“Lowercase: ” + lower);
    }
}

Output :

Uppercase: JAVA PROGRAMMING
Lowercase: java programming

Explanation :

This Java program converts the string “Java Programming” to uppercase and lowercase. It uses built-in string methods toUpperCase() and toLowerCase() to perform the conversions and displays the results.

14. Write a program to remove all occurrences of a specified character from a string?

Algorithm :

  • Start
  • Declare a string str with the value “Hello World”.
  • Declare a character variable target and assign it the character ‘o’.
  • Use replaceAll() to remove all occurrences of target from str.
  • Store the result in result.
  • Print the modified string.
  • End

Program :

  public class RemoveCharacter {
   public static void main(String[] args) {
        String str = “Hello World”;
        char target = ‘o’;
        String result = str.replaceAll(String.valueOf(target), “”);
        System.out.println(“String after removal: ” + result);
    }
}

Output :

String after removal: Hell Wrld

Explanation :

This program removes all occurrences of a specific character (‘o’) from the string “Hello World” using replaceAll(), then prints the updated string without that character.

15. Write a program to check if a string is a substring of another string?

Algorithm :

  • Start
  • Declare str1 as “Hello World” and str2 as “World”.
  • Check if str1 contains str2 using the .contains() method.
  • If true, print that str2 is a substring of str1.
  • Otherwise, print that it is not a substring.  6.  End

Program :

   public class SubstringCheck {
    public static void main(String[] args) {
        String str1 = “Hello World”;
        String str2 = “World”;
        if (str1.contains(str2)) {
            System.out.println(str2 + ” is a substring of ” + str1);
        } else {
            System.out.println(str2 + ” is not a substring of ” + str1);
        }
    }
}

Output :

World is a substring of Hello World

Explanation :

         This program checks if one string (str2) is present inside another string (str1) using Java’s contains() method, and prints the result accordingly.

16. Write a program to find the length of the longest substring without repeating characters?

Algorithm :

  • Start
  • Initialize str = “abcabcbb”, set = empty HashSet, maxLength = 0, left = 0.
  • Iterate over each character in str using right pointer:
    • If str[right] is already in set, remove str[left] from set and increment left.
    • Add str[right] to set.
    • Update maxLength with the maximum of current maxLength and right – left + 1.
  • After the loop, print maxLength.
  • End

Program :

   import java.util.HashSet;
   public class LongestSubstring {
    public static void main(String[] args) {
        String str = “abcabcbb”;
        HashSet<Character> set = new HashSet<>();
        int maxLength = 0;
        int left = 0;
        for (int right = 0; right < str.length(); right++) {
            while (set.contains(str.charAt(right))) {
                set.remove(str.charAt(left));
                left++;
            }
            set.add(str.charAt(right));
            maxLength = Math.max(maxLength, right – left + 1);
        }
        System.out.println(“Length of longest substring without repeating characters: ” + maxLength);
    }
}

Output :

Length of longest substring without repeating characters: 3

Explanation :

       This program finds the length of the longest substring in a given string without repeating characters using the sliding window technique and a HashSet to track unique characters. It moves two pointers (left and right) to maintain the longest valid substring dynamically.

17. Write a program to count the number of vowels and consonants in a string?

Algorithm :

  • Start
  • Define str = “Hello World”.
  • Initialize counters: vowels = 0, consonants = 0.
  • Loop through each character of the string:
    • Convert character to lowercase.
    • If it’s a letter (a to z):
      • If it is in “aeiou”, increment vowels.
      • Otherwise, increment consonants.
  •  After the loop, print the number of vowels and consonants.
  •  End

Program :

       public class VowelConsonantCount {
        public static void main(String[] args) {
        String str = “Hello World”;
        int vowels = 0, consonants = 0;
        for (int i = 0; i < str.length(); i++) {
            char ch = Character.toLowerCase(str.charAt(i));
            if (ch >= ‘a’ && ch <= ‘z’) {
                if (“aeiou”.indexOf(ch) != -1) {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }
        System.out.println(“Vowels: ” + vowels);
        System.out.println(“Consonants: ” + consonants);
    }
}

Output :

    Vowels: 3
    Consonants: 7

Explanation :

        This program counts the number of vowels and consonants in the string “Hello World”. It ignores spaces and non-letter characters and uses a loop to check each character, converting it to lowercase for uniform comparison.

18. Write a program to check if two strings are rotations of each other?

Algorithm :

  • Start
  • Define two strings: str1 = “ABCD” and str2 = “CDAB”.
  • Check if both strings are of the same length.
  • If yes, concatenate str1 with itself: str1 + str1 = “ABCDABCD”.
  • Check if str2 is a substring of the concatenated string.
  • If true, print “The strings are rotations of each other.”
  • Else, print “The strings are not rotations of each other.”
  • End

Program :

   public class StringRotation {
       public static void main(String[] args) {
        String str1 = “ABCD”;
        String str2 = “CDAB”;
        if (str1.length() == str2.length() && (str1 + str1).contains(str2)) {
            System.out.println(“The strings are rotations of each other.”);
        } else {
            System.out.println(“The strings are not rotations of each other.”);
        }
    }
}

Output :

The strings are rotations of each other.

Explanation :

          The program checks whether two strings are rotations of each other. It works by first ensuring both strings have the same length. Then it concatenates the first string with itself — this creates a string that would include all possible rotations. If the second string is found within this new string, it confirms the rotation. For example, “ABCD” rotated becomes “CDAB”, and “ABCDABCD” contains “CDAB”, so the output is:
“The strings are rotations of each other.” 

19. Write a program to find the first repeated character in a string?

Algorithm :

  • Start
  • Initialize a string str = “helloworld”.
  • Create an empty HashSet named set to store characters.
  • Loop through each character in the string using a for loop.
  • For each character at index i:
    a. Check if set already contains str.charAt(i).
    b. If yes, print “First repeated character: ” and the character, then break the loop.
    c. If no, add the character to the set.
  • End

Program :

      import java.util.HashSet;
      public class FirstRepeatedChar {
      public static void main(String[] args) {
        String str = “helloworld”;
        HashSet<Character> set = new HashSet<>();
        for (int i = 0; i < str.length(); i++) {
            if (set.contains(str.charAt(i))) {
                System.out.println(“First repeated character: ” + str.charAt(i));
                break;
            }
            set.add(str.charAt(i));
        }
    }
}

Output :

First repeated character: l

Explanation :

       This Java program finds the first character that repeats in the given string “helloworld”. It uses a HashSet to keep track of characters that have already appeared. As it loops through the string, it checks if the current character exists in the set. If it does, that means it’s the first character to repeat, and it is printed. Otherwise, it adds the character to the set and continues. For this example, ‘l’ is the first character that repeats.

20. Write a program to check if a string contains only digits?

Algorithm :

  • Start
  • Initialize the string str = “12345”.
  • Use the matches() method with the regex pattern \\d+:
    • \\d+ means one or more digits.
  • If str.matches(“\\d+”) returns true:
    • Print “The string contains only digits.”
  • Else:
  • Print “The string does not contain only digits.”
  • End

Program :

  public class StringDigitsCheck {
    public static void main(String[] args) {
        String str = “12345”;
        if (str.matches(“\\d+”)) {
            System.out.println(“The string contains only digits.”);
        } else {
            System.out.println(“The string does not contain only digits.”);
        }
    }
}

Output :

The string contains only digits.

Explanation :

            This Java program checks whether a given string contains only numeric digits using a regular expression (\\d+). The matches() method is used to compare the string against this pattern. If the entire string is composed of digits (0–9), it prints a confirmation message. In this example, since “12345” contains only digits, it will print: “The string contains only digits.”

21. Write a program to swap two strings without using a temporary variable?

Algorithm :

  • Start
  • Initialize str1 = “Hello” and str2 = “World”.
  • Concatenate str1 and str2 and store it back in str1:
    • Now str1 = “HelloWorld”.
  • Extract original str1 from the new str1 using substring:
    • str2 = str1.substring(0, str1.length() – str2.length()) → “Hello”
  • Extract original str2 from the new str1 using substring:
    • str1 = str1.substring(str2.length()) → “World”
  • Print swapped values of str1 and str2.
  • End

Program :

public class StringSwap {
    public static void main(String[] args) {
        String str1 = “Hello”;
        String str2 = “World”;
        str1 = str1 + str2;  // Concatenate both strings
        str2 = str1.substring(0, str1.length() – str2.length());  // Extract the original str1
        str1 = str1.substring(str2.length());  // Extract the original str2
        System.out.println(“After swapping:”);
        System.out.println(“str1: ” + str1);
        System.out.println(“str2: ” + str2);
    }
}

Output :

After swapping:
str1: World
str2: Hello

Explanation :

This program swaps two strings without using a temporary variable. It first concatenates the two strings, then uses substring operations to extract and reassign the original values, effectively swapping them. This is a clever trick that avoids the use of an extra variable by manipulating string lengths.

22. Write a program to check if a string is a valid number (integer or floating-point)?

Algorithm :

  • Start
  • Initialize the string: str = “123.45”
  • Use a try-catch block:
    • Try to convert the string to a number using Double.parseDouble(str)
  • If conversion is successful:
    • Print “The string is a valid number.”
  • If a NumberFormatException occurs:
    • Print “The string is not a valid number.”
  • End

Program :

    public class ValidNumberCheck {
      public static void main(String[] args) {
                String str = “123.45”;
                try {
                        Double.parseDouble(str);
                        System.out.println(“The string is a valid number.”);
                 } catch (NumberFormatException e) {
            System.out.println(“The string is not a valid number.”);
        }
    }
}

Output :

The string is a valid number.

Explanation :

     This program checks if a string represents a valid number by attempting to parse it into a double. If the parsing is successful, the string is valid; otherwise, a NumberFormatException is caught, indicating that the string is not a valid numeric format.

23. Write a program to reverse a String in java without using reverse() method?

Algorithm :

  • Start
  • Define the input string str = “Hello World”
  • Initialize an empty string reversedStr = “”
  • Loop through the original string from the last character to the first:
    • For each character, append it to reversedStr
  • After the loop, print the original and reversed strings
  • End

Program :

public class ReverseString {
       public static void main(String[] args) {
        String str = “Hello World”;
        String reversedStr = “”;   
        for (int i = str.length() – 1; i >= 0; i–) {
            reversedStr += str.charAt(i);  // Append each character to reversedStr
        }
        System.out.println(“Original String: ” + str);
        System.out.println(“Reversed String: ” + reversedStr);
    }
}

Output :

Original String: Hello World
Reversed String: dlroW olleH

Explanation :

             This program reverses a string manually by iterating from the end of the string to the beginning and appending each character to a new string. The result is the reversed version of the original input string.

24. The count-and-say sequence is a series of strings where each string is the result of “saying” the previous string. Write a function to generate the nth string in the count-and-say sequence?

Algorithm :

  • Start
  • Define a recursive function countAndSay(n):
    • If n == 1, return “1” (base case)
    • Call countAndSay(n – 1) to get the previous term
  • Initialize:
    • currentChar as the first character of the previous term
    • count = 1, result as an empty StringBuilder
  • Loop through the remaining characters of the previous term:
    • If the character is same as currentChar, increment count
    • Else:
      • Append count and currentChar to result
      • Update currentChar to the new character, reset count to 1
  • After the loop, append the last counted group to result
  • Return the result as a string
  • In main, print the first 6 terms using a loop
  • End

Program :

         public class CountAndSay {
       public static String countAndSay(int n) {
        if (n == 1) {
            return “1”;
        }
        String previous = countAndSay(n – 1);
        StringBuilder result = new StringBuilder();
        char currentChar = previous.charAt(0);
        int count = 1;
        for (int i = 1; i < previous.length(); i++) {
            if (previous.charAt(i) == currentChar) {
                count++;
            } else {
                result.append(count).append(currentChar);
                currentChar = previous.charAt(i);
                count = 1;
            }
        }
        result.append(count).append(currentChar);
        return result.toString();
    }
    public static void main(String[] args) {
        for (int i = 1; i <= 6; i++) {
            System.out.println(“Term ” + i + “: ” + countAndSay(i));
        }
    }
}

Output for n = 1 to n = 6 :

Term 1: 1
Term 2: 11
Term 3: 21
Term 4: 1211
Term 5: 111221
Term 6: 312211

Explanation :

The CountAndSay program generates and prints the first six terms of the “count and say” sequence. Execution starts from the main method where a loop runs from 1 to 6. For each value of i, the countAndSay method is called recursively. The base case is when n == 1, which returns “1”. For higher values, the method gets the previous term and processes it by counting consecutive characters. It appends the count followed by the character to build the next term. This process continues until the nth term is built and returned. The result is printed in the format Term i: value.

25. Write a program to check if a string is a palindrome using StringBuilder?

Algorithm :

  • Start
  • Define the input string as “madam”
  • Create a StringBuilder object with the input string
  • Reverse the string using StringBuilder.reverse()
  • Convert the reversed string back to String
  • Compare the original string with the reversed string
  • If they are equal:
    • Print that the string is a palindrome
  •  Else:
    • Print that it is not a palindrome
  • End

Program :

public class PalindromeExample {
    public static void main(String[] args) {
        String input = “madam”;
        StringBuilder sb = new StringBuilder(input);
        sb.reverse();
        if (input.equals(sb.toString())) {
            System.out.println(input + ” is a palindrome.”);
        } else {
            System.out.println(input + ” is not a palindrome.”);
        }
    }
}

Output :

madam is a palindrome.

Explanation :

         The PalindromeExample program checks whether the input string “madam” is a palindrome — a word that reads the same forwards and backwards. It does this by:
1.Creating a StringBuilder from the input string.
2.Reversing the string using sb.reverse().
3.Comparing the reversed string with the original string using equals().
 If both strings are equal, it confirms the input is a palindrome; otherwise, it is not. This is a simple and efficient way to check for palindromes in Java using built-in classes.

26. Write a program to remove all occurrences of a specific character from a string using StringBuilder?

Algorithm :

  • Start
  • Initialize a String variable input with value “programming”.
  • Set the charToRemove as ‘g’.
  • Create a StringBuilder object sb using the input string.
  •  Find the index of the first occurrence of ‘g’ in the StringBuilder using indexOf().
  •  Loop while index is not -1 (i.e., while ‘g’ is found):
    • Delete the character at that index using deleteCharAt(index).
    • Recalculate the index of ‘g’ in the updated string.
  •  Exit the loop when no more ‘g’ characters are found.
  •  Print the final string using toString().
  • End

Program :

    public class RemoveCharacterExample {
    public static void main(String[] args) {
        String input = “programming”;
        char charToRemove = ‘g’;
        StringBuilder sb = new StringBuilder(input); 
        int index = sb.indexOf(String.valueOf(charToRemove));
        while (index != -1) {
            sb.deleteCharAt(index);
            index = sb.indexOf(String.valueOf(charToRemove));
        }
        System.out.println(“After removal: ” + sb.toString());
    }
}

Output :

After removal: prorammin

Explanation :

        This program removes all occurrences of a specified character (‘g’) from a string using a StringBuilder. It continuously searches for the character’s index and deletes it until no more are found. This method is efficient and avoids creating multiple string copies.

27. Write a program to reverse the words in a sentence using StringBuilder?

Algorithm :

  • Start
  • Initialize a string input with “Java is fun”.
  • Create a StringBuilder object sb with the input string.
  • Split the input string by spaces using split(” “), and store the result in a String[] named words.
  • Clear the contents of sb using setLength(0) to reuse it.
  • Iterate over the words array in reverse order:
    • Append each word to sb followed by a space.
  • Trim the final string to remove any trailing spaces.
  • Print the reversed sentence.
  • End

Program :

public class ReverseWordsExample {
    public static void main(String[] args) {
        String input = “Java is fun”;
        StringBuilder sb = new StringBuilder(input);
        String[] words = input.split(” “);
        sb.setLength(0);  // Clear the StringBuilder
        for (int i = words.length – 1; i >= 0; i–) {
            sb.append(words[i]).append(” “);
        }
        System.out.println(“Reversed sentence: ” + sb.toString().trim());
    }
}      

Output :

Reversed sentence: fun is Java

Explanation :

This program reverses the words in a sentence. It first splits the original sentence into individual words using spaces as delimiters. Then, it appends the words in reverse order into a StringBuilder and prints the resulting sentence after trimming any extra spaces. For example, “Java is fun” becomes “fun is Java”.

28. Write a program to check if two strings are anagrams of each other using StringBuilder?

Algorithm :

  • Start
  • Initialize two strings: str1 = “listen” and str2 = “silent”.
  • Create StringBuilder objects sb1 and sb2 for both strings.
  • Convert both sb1 and sb2 to character arrays chars1 and chars2.
  • Sort both character arrays using Arrays.sort().
  • Compare the sorted arrays using Arrays.equals().
  •  If they are equal, print that the strings are anagrams.
  • Otherwise, print that the strings are not anagrams.
  • End

Program :

     import java.util.Arrays;
     public class AnagramCheck {
     public static void main(String[] args) {
        String str1 = “listen”;
        String str2 = “silent”;
        StringBuilder sb1 = new StringBuilder(str1);
        StringBuilder sb2 = new StringBuilder(str2);
        // Sort the characters of both strings
        char[] chars1 = sb1.toString().toCharArray();
        char[] chars2 = sb2.toString().toCharArray();
        Arrays.sort(chars1);
        Arrays.sort(chars2);
        if (Arrays.equals(chars1, chars2)) {
            System.out.println(str1 + ” and ” + str2 + ” are anagrams.”);
        } else {
            System.out.println(str1 + ” and ” + str2 + ” are not anagrams.”);
        }
    }
}

Output :

 listen and silent are anagrams.

Explanation :

This program checks whether two strings are anagrams. An anagram means both strings contain the same characters in a different order. It converts both strings to character arrays, sorts them, and compares the sorted arrays. If they match, the strings are anagrams. For example, “listen” and “silent” are anagrams.

29. Write a program to print the reverse of a string using StringBuilder?

Algorithm :

  • Start
  • Initialize a string input = “Hello, World!”.
  • Create a StringBuilder object sb using the input string.
  • Call sb.reverse() to reverse the characters in the string.
  • Print the reversed string using sb.toString().
  • End

Program :

public class ReverseStringExample {
    public static void main(String[] args) {
        String input = “Hello, World!”;
        StringBuilder sb = new StringBuilder(input);  
        sb.reverse();  // Reversing the string 
        System.out.println(“Reversed string: ” + sb.toString());
    }
}

Output :

 Reversed string: !dlroW ,olleH

Explanation :

This program reverses a string using StringBuilder. The reverse() method efficiently reverses the characters in place. For example, “Hello, World!” becomes “!dlroW ,olleH” after reversal.

30. Write a program to remove all white spaces from a string using StringBuilder?

Algorithm :

  • Start
  • Define the input string: “Java programming is fun!”.
  • Create a StringBuilder object sb with the input string.
  • Find the first index of a space character (” “).
  • While a space exists:
    • Delete the character at that index.
    • Find the next space in the updated string.
  • Print the final string without spaces.
  • End

Program :

public class RemoveWhitespaceExample {
    public static void main(String[] args) {
        String input = “Java programming is fun!”;
        StringBuilder sb = new StringBuilder(input);
        int index = sb.indexOf(” “);
        while (index != -1) {
            sb.deleteCharAt(index);
            index = sb.indexOf(” “);
        }
        System.out.println(“Without spaces: ” + sb.toString());
    }
}

Output :

Without spaces: Javaprogrammingisfun!

Explanation :

     This program removes all whitespace (spaces) from a string by repeatedly finding and deleting space characters using a StringBuilder. The result is a continuous string without any spaces.

31. Write a program to count the occurrences of a character in a string using StringBuilder?

Algorithm :

  • Start
  • Define the input string: “programming”.
  • Define the character to count: ‘r’.
  • Create a StringBuilder object sb using the input string.
  • Initialize a count variable to 0.
  • Loop through each character in sb:
    • If the character matches ‘r’, increment count.
  •  After the loop, print the count of ‘r’.
  •  End

Program :

public class CountCharacterExample {
     public static void main(String[] args) {
        String input = “programming”;
        char charToCount = ‘r’;
        StringBuilder sb = new StringBuilder(input);
        int count = 0;
        for (int i = 0; i < sb.length(); i++) {
            if (sb.charAt(i) == charToCount) {
                count++;
            }
        }
        System.out.println(“The character ‘” + charToCount + “‘ appears ” + count + ” times.”);
    }
}

Output :

The character ‘r’ appears 2 times.

Explanation :

The program is designed to count the number of times a specific character (‘r’) appears in the string “programming”. It uses a StringBuilder to hold the string and iterates through each character using a for loop. Whenever the character at the current index matches ‘r’, it increments a counter. Finally, it prints how many times ‘r’ appeared in the string. This is a simple example of character frequency counting in Java.

32. Write a program to count the total number of vowels in a string using StringBuilder?

Algorithm :

  • Start
  • Declare and initialize a String variable input with the value “programming is fun!”.
  • Create a StringBuilder object sb using input.
  • Initialize an integer variable vowelCount to 0.
  • Define a String variable vowels containing all vowel characters: “aeiouAEIOU”.
  • Loop through each character in the sb using a for loop:
    • For each character at index i, check if it is present in the vowels string using vowels.indexOf(sb.charAt(i)).
    • If the result is not -1, it means the character is a vowel. Increment vowelCount by 1.
  • After the loop ends, print the total number of vowels using System.out.println.
  • End

Program :

public class CountVowelsExample {
    public static void main(String[] args) {
        String input = “programming is fun!”;
        StringBuilder sb = new StringBuilder(input);    
        int vowelCount = 0;
        String vowels = “aeiouAEIOU”;   
        for (int i = 0; i < sb.length(); i++) {
            if (vowels.indexOf(sb.charAt(i)) != -1) {
                vowelCount++;
            }
        }
        System.out.println(“The number of vowels: ” + vowelCount);
    }
}

Output :

 The number of vowels: 6

Explanation :

               This Java program counts the number of vowels in the input string “programming is fun!”. It uses a StringBuilder to store the string and checks each character in the string using a for loop. The vowels string (“aeiouAEIOU”) contains all vowel characters (both uppercase and lowercase). If the current character is found in the vowels string using indexOf(), the vowelCount is incremented. Finally, the program prints the total number of vowels in the string.

33. Write a program to capitalize the first letter of each word in a sentence using StringBuilder?

Algorithm :

  •  Start
  • Declare a String variable input and assign it “java programming is fun”.
  • Create a StringBuilder object sb using input.
  • Split input into individual words using split(” “) and store them in a String[] array named words.
  • Clear the StringBuilder by calling sb.setLength(0).
  • For each word in the words array:
    • Convert the first character to uppercase using word.substring(0, 1).toUpperCase().
    • Append the rest of the word using word.substring(1).
    • Append a space ” ” after each capitalized word.
  • After the loop, print the result by trimming the final string (sb.toString().trim()).
  • End

Program :

  public class CapitalizeWordsExample {
    public static void main(String[] args) {
        String input = “java programming is fun”;
        StringBuilder sb = new StringBuilder(input);
        String[] words = input.split(” “);
        sb.setLength(0);  // Clear the StringBuilder 
        for (String word : words) {
            sb.append(word.substring(0, 1).toUpperCase())
              .append(word.substring(1)).append(” “);
        }
        System.out.println(“Capitalized words: ” + sb.toString().trim());
    }
}

Output :

Capitalized words: Java Programming Is Fun

Explanation :

           The CapitalizeWordsExample program is designed to capitalize the first letter of each word in a given sentence. It starts by defining the input string “java programming is fun”. The input is then split into individual words using the split(” “) method, which separates the string based on spaces. A StringBuilder is used for efficient string manipulation, and it’s cleared before constructing the new string. The program iterates over each word, converts the first character to uppercase using substring(0, 1).toUpperCase(), appends the rest of the word unchanged, and adds a space after each word. Finally, it trims any trailing space and prints the result. The output of this program is “Java Programming Is Fun”, effectively capitalizing the first letter of each word in the original sentence.

34. Write a program to remove duplicate characters from a string using StringBuilder?

Algorithm :

  • Start
  • Initialize a string input = “programming”.
  • Create an empty StringBuilder named sb to store unique characters.
  • Loop through each character of the input string:
  • For each character currentChar at position i:
    • Check if currentChar is not already present in sb using sb.indexOf(String.valueOf(currentChar)).
    • If not present (returns -1), append currentChar to sb.
  •  After the loop completes, print the content of sb (which now contains characters without duplicates).
  • End

Program :

   public class RemoveDuplicatesExample {
      public static void main(String[] args) {
        String input = “programming”;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char currentChar = input.charAt(i);
            if (sb.indexOf(String.valueOf(currentChar)) == -1) {
                sb.append(currentChar);
            }
        }
        System.out.println(“String without duplicates: ” + sb.toString());
    }
}

Output :

String without duplicates: progamin

Explanation :

This program removes duplicate characters from the input string “programming” while keeping the first occurrence of each character in order. It uses a StringBuilder to dynamically build the new string. For every character in the input, it checks whether that character already exists in the StringBuilder. If not, it appends it. This ensures that only the first occurrence of each character is retained. For example, ‘r’, ‘g’, and ‘m’ appear multiple times in “programming”, but are added only once. The final output is: String without duplicates: progamin.

35. Write a program to reverse a String using StringBuffer?

Algorithm :

  • Start
  • Declare a String variable str and assign it the value “Hello”.
  • Create a StringBuffer object sb and initialize it with the string str.
  • Reverse the string using sb.reverse().
  • Print the reversed string.
  • End

Program :

public class ReverseString {
    public static void main(String[] args) {
        String str = “Hello”;
        StringBuffer sb = new StringBuffer(str);
        System.out.println(sb.reverse());
    }
}

Output :

olleH

Explanation :

This Java program reverses a string using the built-in StringBuffer class. It first stores the string “Hello” in a variable and then creates a StringBuffer object with this string. The StringBuffer class provides a convenient method reverse(), which reverses the characters of the string in place. The reversed string is then printed to the console. The output will be: olleH.

36. Write a program to append a String to another String using StringBuffer?

Algorithm :

  • Start the Program Execution
    • The program begins execution from the main method.
  • Create a StringBuffer Object
    • StringBuffer sb = new StringBuffer(“Hello”);
      • A new StringBuffer object named sb is created.
      • The initial content of sb is set to the string “Hello”.
  • Append a String
    • sb.append(” World”);
      • The append() method is called on the sb object.
      • The string ” World” is added (concatenated) to the end of the existing content.
      • Now, the content of sb becomes “Hello World”.
  • Print the Result
    • System.out.println(sb);
      • The current content of the sb object (“Hello World”) is printed to the console.
  • End Program
    • The main method finishes, and the program terminates.

Program :

public class AppendString {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        sb.append(” World”);
        System.out.println(sb);
        }
      }

 Output :

Hello World

Explanation :

        This Java program demonstrates how to append one string to another using the StringBuffer class. The program initializes a StringBuffer with the string “Hello” and then appends ” World” to it using the append() method. The resulting string “Hello World” is then printed to the console.

37. Write a program to delete a substring using StringBuffer?

Algorithm :

  • Start
  • Create a StringBuffer object sb and initialize it with “Hello World”.
  • Call the delete(5, 11) method to remove the substring from index 5 (inclusive) to 11 (exclusive).
  • Print the updated content of sb.   
  • End

Program :

public class DeleteSubstring {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello World”);
        sb.delete(5, 11);
        System.out.println(sb);
    }
}

Output :

Hello

Explanation :

     This program removes a part of the string “Hello World” using the delete() method of the StringBuffer class. It deletes characters starting from index 5 up to (but not including) index 11. In this case, it removes ” World”, leaving only “Hello” in the buffer.

38. Write a program to replace a substring using StringBuffer?

Algorithm :

  •  Start
  • Create a StringBuffer object sb with the initial value “Hello World”.
  • Use the replace(6, 11, “Java”) method to replace the substring from index 6 (inclusive) to 11 (exclusive) with “Java”.
  • Print the updated content of sb.
  • End

Program :

   public class ReplaceSubstring {
       public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello World”);
        sb.replace(6, 11, “Java”);
        System.out.println(sb);
    }
}

Output :

Hello Java

Explanation :

         This program replaces a part of the original string “Hello World” with “Java”. The replace method changes the substring from index 6 to 10 (i.e., “World”) with the new word “Java”. So the final result becomes “Hello Java”.Output: Hello Java

39. Write a program to replace the character at a specific index in a string using StringBuffer?

Algorithm :

  •  Start
  • Initialize a String variable input with the value “hello world”.
  • Create a StringBuffer object sb using the input string.
  • Use the setCharAt(6, ‘W’) method to replace the character at index 6 with ‘W’.
  • Print the updated string using sb.toString().
  • End

Program :

public class ReplaceCharacter {
    public static void main(String[] args) {
        String input = “hello world”;
        StringBuffer sb = new StringBuffer(input);
        sb.setCharAt(6, ‘W’);
        System.out.println(“String after replacement: ” + sb.toString());
    }
}

Output :

String after replacement: hello World

Explanation :

      This program replaces a single character in a string. The string “hello world” has ‘w’ at index 6 (since indexing starts at 0). The setCharAt method is used to replace ‘w’ with ‘W’. The result is “hello World”.

40. Write a program to insert a string at a specified index in a given string using StringBuffer?

Algorithm :

  • Start
  • Initialize a String variable input with “Hello!”.
  • Create a StringBuffer object sb using input.
  • Call sb.insert(6, “World “) to insert “World ” at index 6.
  • Print the updated string using sb.toString().
  • End

Program :

   public class InsertString {
    public static void main(String[] args) {
        String input = “Hello!”;
        StringBuffer sb = new StringBuffer(input);
        sb.insert(6, “World “);
        System.out.println(“String after insertion: ” + sb.toString());
         }
    }

Output :

String after insertion: Hello World!

Explanation :

          This program inserts a substring into a given string using the StringBuffer class. The original string is “Hello!”, which has a length of 6. The program inserts “World ” at index 6 (the end of the string), resulting in “Hello!World “. The insert() method shifts existing characters as needed to accommodate the new string.

41. Write a program to concatenate two strings using StringBuffer?

Algorithm :

  • Start
  • Define two strings:
    • input1 = “Hello”
    • input2 = “World”
  • Create a StringBuffer object sb initialized with input1.
  • Use sb.append(” “) to add a space after input1.
  • Use sb.append(input2) to add input2 to the buffer.
  • Convert the StringBuffer to a string using toString() and print the result.
  • End

Program :

      public class ConcatenateStrings {
    public static void main(String[] args) {
        String input1 = “Hello”;
        String input2 = “World”;
        StringBuffer sb = new StringBuffer(input1);
        sb.append(” “).append(input2);   
        System.out.println(“Concatenated string: ” + sb.toString());
          }
    }

Output :

 Concatenated string: Hello World

Explanation :

        The program demonstrates how to concatenate two strings using StringBuffer, which is mutable and efficient for multiple modifications. First, it creates a StringBuffer containing “Hello”. Then it appends a space and the word “World”, resulting in the final string “Hello World”. Finally, it prints the concatenated string.

42. Write a program to remove a specific substring from a string using StringBuffer?

Algorithm :

  • Start
  • Initialize the input string
    • Input: “Hello, World!”
    • Action: Store this in a String variable.
    • String input = “Hello, World!”;
  • Convert the string to a mutable object
    • Action: Create a StringBuffer object from the input string so it can be modified. StringBuffer sb = new StringBuffer(input);
    • Value of sb: “Hello, World!”
  •  Find the starting index of the substring to remove
    • Substring to remove: “World”
    • Action: Use indexOf(“World”) to find where “World” begins in sb.
    • int start = sb.indexOf(“World”);
    • Result: start = 7 (index of “W” in “World”)
  • Check if the substring exists
    • if (start != -1) {
    • Condition: Check if the substring was found (start != -1)
    • Result: True (since start = 7)
  • Remove the substring
    • Action : Call delete(start, start + length) to remove “World”
    • “World”.length() = 5
    • start + 5 = 12
    • sb.delete(start, start + “World”.length());
    • Effect: Removes characters from index 7 to 11 (inclusive), resulting in:
    • New value of sb: “Hello, !”
  •  Output the result
    • Action: Convert sb to string and print.
    • System.out.println(“String after removal: ” + sb.toString());
    • Output: String after removal: Hello, !
  • End

Program :

      public class RemoveSubstring {
     public static void main(String[] args) {
        String input = “Hello, World!”;
        StringBuffer sb = new StringBuffer(input);  
        int start = sb.indexOf(“World”);
        if (start != -1) {
            sb.delete(start, start + “World”.length());
        } 
        System.out.println(“String after removal: ” + sb.toString());
    }
}

Output :

 String after removal: Hello, !

Explanation :

This Java program removes the substring “World” from the string “Hello, World!” using StringBuffer. First, it converts the input string into a StringBuffer to allow modification. It then finds the starting index of “World” using the indexOf() method. If the substring is found, the delete() method is used to remove it by specifying the start and end positions. The delete() method removes characters from index 7 to 12. Finally, the modified string is printed using System.out.println(). The output is “Hello, !”, with “World” successfully removed.

43. Write a program to set the length of a StringBuffer?

Algorithm :

  • Start
  • Initialize a StringBuffer object sb with the string “Hello”.
    • sb = new StringBuffer(“Hello”)
  • Call the method setLength(3) on the sb object.
    • This reduces the length of sb to 3 characters.
    • The original content “Hello” becomes “Hel”.
  • Print the modified content of sb using System.out.println(sb).
  • End

Program :

  public class SetLength {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        sb.setLength(3);
        System.out.println(sb);
    }
}

Output :

 Hel

Explanation :

      This Java program demonstrates how to modify the length of a StringBuffer object using the setLength() method. It begins by initializing a StringBuffer with the content “Hello”. The setLength(3) method is then called to reduce the length of the buffer to 3 characters. As a result, the last two characters, ‘l’ and ‘o’, are truncated, leaving “Hel” as the remaining content. The modified string is then printed using System.out.println(). This shows how setLength() can be used to trim or extend the buffer.

44. Write a program to ensure capacity of a StringBuffer?

Algorithm :

  • Start
  • Create an empty StringBuffer object sb.
    • sb = new StringBuffer()
  • Call the method ensureCapacity(50) on sb.
    • This ensures the internal buffer can hold at least 50 characters without resizing.
  • Print the current capacity of the buffer using System.out.println(sb.capacity()).
  • End

Program :

   public class EnsureCapacity {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        sb.ensureCapacity(50);
        System.out.println(sb.capacity());
    }
}

Output :

50

Explanation :

          This Java program demonstrates the use of the ensureCapacity() method of the StringBuffer class. It begins by creating an empty StringBuffer object. The ensureCapacity(50) method is then called to make sure the internal buffer can hold at least 50 characters. If the current capacity is less than 50, it is increased based on the formula: (oldCapacity * 2) + 2, ensuring it meets or exceeds the requested capacity. Since the default capacity of an empty StringBuffer is 16, it gets increased to 50. Finally, the program prints the new capacity, which is 50. This method is useful for optimizing performance when the expected size is known in advance.

45. Write a program to get the capacity of StringBuffer?

Algorithm :

  • Start
  • Create a StringBuffer object sb and initialize it with the string “Hello World”.
    • sb = new StringBuffer(“Hello World”)
  • Extract a substring from sb using the substring(6, 11) method.
    • This returns the characters from index 6 to 10 (end index is exclusive).
    • Resulting substring is “World”.
  • Store the extracted substring in a String variable result.
  • Print the value of result using System.out.println(result).
  • End

Program :

public class Substring {
      public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello World”);
        String result = sb.substring(6, 11);
        System.out.println(result);
    }
}

Output :

World

Explanation :

This Java program demonstrates how to extract a portion of a string using the substring() method on a StringBuffer object. The StringBuffer is initialized with the text “Hello World”. The program then uses substring(6, 11) to extract characters starting at index 6 up to, but not including, index 11. This returns the substring “World”, which is stored in the variable result. Finally, it prints “World” to the console. This shows how to work with substrings in mutable string buffers by extracting parts of the text as immutable String values.

46. Write a program to reverse a StringBuffer without using reverse() method?

Algorithm :

  • Start
  • Create a StringBuffer object sb and initialize it with the string “Hello”.
  • Create another empty StringBuffer object reversed to store the reversed string.
  • Initialize a for loop with index i starting from sb.length() – 1 down to 0.
  • In each iteration, append the character at index i of sb to the reversed buffer.
    • Use sb.charAt(i) to get the character.
  • Continue the loop until all characters are appended in reverse order.
  • Print the reversed string using System.out.println(reversed).
  • End

Program :

public class ReverseWithoutReverse {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        StringBuffer reversed = new StringBuffer();
        for (int i = sb.length() – 1; i >= 0; i–) {
            reversed.append(sb.charAt(i));
        }
        System.out.println(reversed);
    }
}

Output :

olleH

Explanation :

          This Java program reverses the string “Hello” without using the built-in reverse() method. It initializes a StringBuffer with the word “Hello” and creates another empty StringBuffer named reversed to store the result. A for loop runs from the last index of the original string (sb.length() – 1) down to 0. In each iteration, the character at the current index is fetched using charAt(i) and appended to the reversed buffer. After the loop completes, the reversed buffer contains the characters in reverse order, which is “olleH”. The final reversed string is then printed to the console.

47. Write a program to convert StringBuffer to String?

Algorithm :

  • Start
  • Create a StringBuffer object sb and initialize it with the string “Hello”.
  • Convert the StringBuffer object sb into a String object using the toString() method.
    • Store the result in a variable str.
  • Print the value of the str variable using System.out.println(str).
  • End

Program :

  public class ConvertToString {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        String str = sb.toString();
        System.out.println(str);
    }
}

Output :

 Hello

Explanation :

This Java program shows how to convert a StringBuffer to a regular String. It begins by creating a StringBuffer object with the content “Hello”. The toString() method is then called on the StringBuffer to convert it into an immutable String object. The result is stored in a variable named str. Finally, the program prints the value of str to the console, which outputs “Hello”. This conversion is useful when you want to switch from mutable string operations to immutable ones, such as when passing the result to methods that expect a String.

48. Write a program to delete a character at a specific index using StringBuffer?

Algorithm :

  • Start
  • Create a StringBuffer object sb and initialize it with the string “Hello”.
  • Call the method deleteCharAt(2) on sb.
    • This removes the character at index 2 (which is ‘l’ in “Hello”).
  • Print the updated StringBuffer using System.out.println(sb).
  • End

Program :

public class DeleteCharAt {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        sb.deleteCharAt(2);
        System.out.println(sb);
    }
}

Output :

 Helo

Explanation :

         This Java program demonstrates how to remove a single character from a specific position in a StringBuffer. It starts by initializing a StringBuffer with the string “Hello”. The deleteCharAt(2) method is then called, which removes the character at index 2. In this case, the character ‘l’ at the third position is deleted, resulting in the string “Helo”. Finally, the updated string is printed to the console. This method is useful when you need to delete a specific character by position from a mutable string.

49. Write a program to append a number to a StringBuffer?

Algorithm :

  • Start
  • Create a StringBuffer object sb and initialize it with the string “Hello”.
  • Append the integer 123 to the sb object using the append() method.
    • This converts the number to a string and adds it to the end of “Hello”.
  • Print the resulting content of sb using System.out.println(sb).
  • End

Program :

   public class AppendNumber {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        sb.append(123);
        System.out.println(sb);
    }
}

Output :

Hello123

Explanation :

            This Java program demonstrates how to append a number to a StringBuffer. It starts by creating a StringBuffer initialized with the text “Hello”. The program then calls the append(123) method, which converts the number 123 to a string and concatenates it to the end of the current buffer. As a result, the content of the StringBuffer becomes “Hello123”. Finally, the program prints the modified buffer to the console. This shows how StringBuffer can efficiently handle appending different types of data, including numbers.

50. Write a program to check if StringBuffer is empty?

Algorithm :

  • Start
  • Create an empty StringBuffer object sb.
    • No initial content is provided.
  • Check whether the buffer is empty by evaluating sb.length() == 0.
    • This returns true if the buffer has no characters.
  • Print the result of the check using System.out.println().
  • End

Program :

   public class IsEmpty {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        System.out.println(sb.length() == 0);  // Check if it’s empty
    }
}

Output :

True

Explanation :

          This Java program checks whether a StringBuffer is empty. It begins by creating a new StringBuffer without any content, meaning its length is initially 0. The expression sb.length() == 0 is used to determine if the buffer is empty. Since the buffer has no characters, this condition evaluates to true. The result is then printed to the console. This is a simple way to check for emptiness in a StringBuffer, as it does not have a built-in isEmpty() method like String or ArrayList.

51. Write a program to insert a character at a specific position using StringBuffer?

Algorithm :

  •  Start
  • Create a StringBuffer object sb and initialize it with the string “Hello”.
  • Insert the character ‘!’ at index 5 using the insert() method.
    • This adds ‘!’ at the end of the string, since index 5 is right after “Hello”.
  • Print the updated StringBuffer using System.out.println(sb).
  • End

Program :

      public class InsertChar {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        sb.insert(5, ‘!’);
        System.out.println(sb);
    }
}

Output :

Hello!

Explanation :

        This Java program shows how to insert a character into a specific position in a StringBuffer. The buffer is initialized with the string “Hello”, which has a length of 5. The program uses insert(5, ‘!’) to insert the exclamation mark at index 5, which is the end of the string. As a result, the buffer becomes “Hello!”. Finally, the modified buffer is printed to the console. The insert() method is useful for adding characters or strings at any position within a mutable character sequence.

52. Write a program to append a String at the start of a StringBuffer?

Algorithm :

  •  Start
  • Create a StringBuffer object sb and initialize it with the string “World”.
  • Insert the string “Hello ” at index 0 using the insert() method.
    • This adds “Hello ” to the beginning of “World”.
  • Print the updated StringBuffer using System.out.println(sb).
  • End

Program :

    public class AppendAtStart {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“World”);
        sb.insert(0, “Hello “);
        System.out.println(sb);
    }
}

Output :

 Hello World

Explanation :

This Java program demonstrates how to prepend (add at the beginning) text to a StringBuffer. It starts by initializing the buffer with the string “World”. Using the insert(0, “Hello “) method, it inserts “Hello ” at index 0, which places the new text before the existing content. The resulting buffer becomes “Hello World”. Finally, the updated string is printed to the console. This example shows how the insert() method can be used to add text not just in the middle or end, but also at the start of a string.

53. Write a program to get the capacity of StringBuffer?

Algorithm :

  • Start
  • Create a StringBuffer object sb and initialize it with the string “Hello”.
  • Call the capacity() method on the sb object to get its current capacity.
  • Print the capacity using System.out.println(sb.capacity()).
  • End

Program :

   public class Capacity {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        System.out.println(sb.capacity());
    }
}

Output :

21

Explanation :

          This Java program demonstrates how to check the capacity of a StringBuffer. It initializes the buffer with the string “Hello”. Internally, StringBuffer allocates extra memory to allow for efficient string modification. When a string is passed to the constructor, the initial capacity becomes 16 (default) + length of the string. In this case, the length of “Hello” is 5, so the total capacity is 21.

54. Write a program to chain StringBuffer methods?

  •  Start
  • Initialize a StringBuffer object sb with the value “Hello”.
    • sb = new StringBuffer(“Hello”)
  • Append the string ” World” to sb.
    • sb.append(” World”)
    • Now sb contains “Hello World”
  • Delete the character at index 5 (which is a space character).
    • sb.delete(5, 6)
    • Now sb contains “HelloWorld”
  • Insert the string ” Java” at index 5.
    • sb.insert(5, ” Java”)
    • Now sb contains “Hello JavaWorld”
  • Print the final content of sb to the console.
    • System.out.println(sb)
  • End

Program :

public class MethodChaining {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        sb.append(” World”).delete(5, 6).insert(5, ” Java”);
        System.out.println(sb);
    }
}

Output :

Hello JavaWorld

Explanation :

This Java program demonstrates method chaining using the StringBuffer class. It begins by initializing a StringBuffer object with the value “Hello”. It then uses the append() method to add ” World” to the end of the string, resulting in “Hello World”. Next, it calls the delete(5, 6) method, which removes the character at index 5—the space between “Hello” and “World”—yielding “HelloWorld”. Following that, the insert(5, ” Java”) method inserts the string ” Java” at index 5, directly after the word “Hello”, resulting in the final string “Hello JavaWorld”.

55. Write a program to replace a character at a specific index using StringBuffer?

Algorithm :

  • Start
  • Initialize a StringBuffer object sb with the string “Hello”.
    • sb = new StringBuffer(“Hello”)
  • Replace the character at index 1 with the character ‘a’.
    • sb.setCharAt(1, ‘a’)
    • “Hello” becomes “Hallo” (since ‘e’ at index 1 is replaced by ‘a’)
  • Print the modified string buffer.
    • System.out.println(sb)
    • Output: Hallo
  • End

Program :

public class ReplaceCharAt {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        sb.setCharAt(1, ‘a’);
        System.out.println(sb);
    }
}

Output :

 Hallo

Explanation :

       This Java program demonstrates how to modify a specific character in a string using the StringBuffer class. It begins by initializing a StringBuffer object with the string “Hello”. The method setCharAt(1, ‘a’) is then used to replace the character at index 1 (which is ‘e’) with ‘a’. As a result, the string becomes “Hallo”. Finally, the modified string is printed to the console.

56. Write a program to use StringBuffer in a loop for concatenation?

Algorithm :

  • Start
  • Create an empty StringBuffer object sb.
    • sb = new StringBuffer()
  • Start a loop from i = 1 to i = 5 (inclusive):
    • For each iteration:
      • Append the current value of i to sb.
      • Append a space ” ” after the number.
  • After the loop ends, sb will contain the string “1 2 3 4 5 ” (note the trailing space).
  • Print the contents of sb.
    • System.out.println(sb)
  • End

Program :

    public class LoopConcatenation {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i <= 5; i++) {
            sb.append(i).append(” “);
        }
        System.out.println(sb);
    }
}

Output :

 1 2 3 4 5

Explanation :

This Java program illustrates how to build a string of consecutive numbers using a loop and the StringBuffer class. It begins by initializing an empty StringBuffer. A for loop runs from 1 through 5, and during each iteration, the loop appends the current number followed by a space to the buffer. Thanks to method chaining with append(), the numbers are added efficiently. After the loop completes, the buffer contains “1 2 3 4 5 “, which is then printed to the console.

57. Write a program to append a sequence of characters to StringBuffer using appendCodePoint()?

Algorithm :

  • Start
  • Initialize a StringBuffer object sb with the string “Hello”.
    • sb = new StringBuffer(“Hello”)
  • Append a Unicode character with code point 123 to the buffer using:
    • sb.appendCodePoint(123)
    • Unicode code point 123 corresponds to the character ‘{‘.
  • Print the final content of sb.
    • System.out.println(sb)
    • Output: Hello{
  • End

Program :

   public class AppendCodePoint {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        sb.appendCodePoint(123);  // Appends Unicode character ‘{‘
        System.out.println(sb);
    }
}

Output :

Hello{

Explanation :

This Java program demonstrates how to append a Unicode character to a string using the appendCodePoint() method of the StringBuffer class. It starts by creating a StringBuffer initialized with the word “Hello”. The method appendCodePoint(123) is then called, which appends the Unicode character represented by the code point 123. According to the Unicode standard, code point 123 corresponds to the opening curly brace {. As a result, the string becomes “Hello{“. This method is useful when you need to add characters based on their Unicode values, especially when working with internationalization or special symbols.

58. Write a program to find the last occurrence of a character in StringBuffer?

Algorithm :

  • Start
  • Initialize a StringBuffer object sb with the string “Hello World”.
    • sb = new StringBuffer(“Hello World”)
  • Call the method lastIndexOf(“o”) on sb.
    • sb.lastIndexOf(“o”)
    • Finds the last occurrence of the substring “o” in the buffer.
    • The string “Hello World” has two ‘o’ characters:
      • First ‘o’ at index 4 (in “Hello”)
      • Second ‘o’ at index 7 (in “World”)
  • Print the index of the last occurrence.
    • Output: 7
  • End

Program :

public class LastOccurrence {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello World”);
        System.out.println(sb.lastIndexOf(“o”));  // Last occurrence of ‘o’
    }
}

Output :

7

Explanation :

       This Java program uses the lastIndexOf() method of the StringBuffer class to determine the position of the last occurrence of a specific character within a string. It initializes a StringBuffer with the text “Hello World”, then searches for the last occurrence of the character ‘o’. The string contains ‘o’ at two positions: index 4 and index 7. Since lastIndexOf(“o”) returns the highest index where ‘o’ appears, it correctly returns 7. This is useful in string processing when you need to locate the final instance of a particular character or substring.

59. Write a program to remove the last character from a StringBuffer?

Algorithm :

  • Start
  • Initialize a StringBuffer object sb with the string “Hello”.
    • sb = new StringBuffer(“Hello”)
  • Calculate the last character’s index:
    • lastIndex = sb.length() – 1
    • In this case, lastIndex = 5 – 1 = 4
  • Delete the character at lastIndex using:
    • sb.deleteCharAt(lastIndex)
    • Removes the character ‘o’ at index 4
  • Print the updated string buffer.
    • System.out.println(sb)
    • Output: Hell
  • End

Program :

   public class RemoveLastChar {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer(“Hello”);
        sb.deleteCharAt(sb.length() – 1);  // Remove the last character
        System.out.println(sb);
    }
}

Output :

Hell

Explanation :

         This Java program demonstrates how to remove the last character from a string using the StringBuffer class. The buffer is initialized with the word “Hello”. To remove the last character, the program calculates the index of the final character using sb.length() – 1 (which is 4 in this case), then deletes that character using deleteCharAt(). As a result, the character ‘o’ is removed, and the updated string becomes “Hell”. This is a common pattern used when trimming characters, especially in string formatting or cleanup tasks.

60. Write a program to check if two StringBuffer objects are equal?

Algorithm :

  • Start
  • Initialize two StringBuffer objects:
    • sb1 = new StringBuffer(“Hello”)
    • sb2 = new StringBuffer(“Hello”)
  • Convert both sb1 and sb2 to String objects using toString():
    • sb1.toString() → “Hello”
    • sb2.toString() → “Hello”
  • Compare the resulting strings using .equals():
    • “Hello”.equals(“Hello”) → true
  • Print the result of the comparison.
    • Output: true
  • End

Program :

   public class CheckEquality {
    public static void main(String[] args) {
        StringBuffer sb1 = new StringBuffer(“Hello”);
        StringBuffer sb2 = new StringBuffer(“Hello”);   
        System.out.println(sb1.toString().equals(sb2.toString()));
    }
}

Output :

True

Explanation :

     This Java program checks whether two StringBuffer objects contain the same content. Although both sb1 and sb2 are initialized with the string “Hello”, directly comparing them using == or .equals() on the StringBuffer objects would return false, because StringBuffer does not override the equals() method—it compares object references, not content. To compare the actual string values, the program converts both buffers to String using toString(), and then uses the equals() method of the String class, which compares character sequences. Since both strings are “Hello”, the result is true.

Leave a Reply

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