Sitemap

Java Day-43

6 min readNov 26, 2025

--

String_2

Press enter or click to view image in full size

1.1 StringBuffer & StringBuilder

What they ar

  • String → immutable (cannot change)
  • StringBuffer → mutable, thread-safe (synchronized), a little slower
  • StringBuilder → mutable, not thread-safe, faster (used in most programs)

Both StringBuffer and StringBuilder extend AbstractStringBuilder, so they have almost the same methods (append, insert, reverse, capacity, etc.).

1.2 Constructors of StringBuffer

  1. StringBuffer sb1 = new StringBuffer();
  • Creates empty buffer
  • Default capacity = 16 characters
  1. StringBuffer sb2 = new StringBuffer(int initialCapacity)
  • Example: new StringBuffer(25); → capacity = 2

2. StringBuffer sb3 = new StringBuffer(CharSequence cs);

  • CharSequence is an interface implemented by String, StringBuffer, StringBuilder
  • Example: new StringBuffer("Java");

3. StringBuffer sb4 = new StringBuffer(String str);

  • Directly from String

Capacity rule

  • capacity() → returns how many characters can be stored before resizing.
  • Default: 16
  • When capacity is full and we append more data:
  • newCapacity = (oldCapacity * 2) + 2

Example:

  • start: new StringBuffer() → 16
  • after growth: (16 * 2) + 2 = 34

For a buffer created with a string:

  • capacity = 16 + str.length()
    Example: "Java" → length 4 → capacity 16 + 4 = 20

1.3 Important methods

  • int capacity() – current capacity (not length)
  • int length() – current number of stored characters
  • StringBuffer append(String s) – add at end
  • StringBuffer insert(int index, String s) – insert at given index
  • StringBuffer reverse() – reverse the characters
  • String toString() – convert to String

Same methods exist in StringBuilder.

1.4 Performance: StringBuffer vs StringBuilder

To check speed we can use

long t = System.currentTimeMillis();

steps:

  1. Create StringBuilder, append many times in a loop.
  2. Take endTime - startTime.
  3. Do the same with StringBuffer.
  4. Usually StringBuilder is faster because it is not synchronized.

1.5 String class constructors

Common constructors:

String s1 = new String();                  // empty
String s2 = new String("Java"); // from literal
String s3 = new String(new StringBuffer("abc"));
String s4 = new String(new StringBuilder("xyz"));
String s5 = new String(new char[]{'a','b','c'});
String s6 = new String(new byte[]{65,66,67}); // "ABC"

1.6 Useful String logic programs

From your screenshots:

  • Reverse a string (loop from last index to 0)
  • Reverse using StringBuffer / StringBuilder reverse()
  • Find duplicate characters and count the
  • Remove a specific character from the string
  • Check if string contains at least one vowel
  • Sort characters of string (like bubble sort on char[])
  • Count how many times a given character appears
  • Check if string contains any digit (Character.isDigit
  • Count uppercase and lowercase letters
    (Character.isUpperCase, Character.isLowerCase
  • Count vowels and consonant
  • Check if string is palindrome (same forward and backward)

Get Aman Verma’s stories in your inbox

Join Medium for free to get updates from this writer.

1.7 Character class (java.lang.Character)

Important static methods:

  • isDigit(char ch)
  • isUpperCase(char ch)
  • isLowerCase(char ch)
  • toUpperCase(char ch)
  • toLowerCase(char ch)

Used to test each character in a loop.

2. 25 Questions with Java Solutions

I’ll write each as a small static method.
You can put them all inside one class public class StringQuestions { … } and call from main.

Q1. Print default capacity of StringBuffer

static void q1() {
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // 16
}

Q2. Create StringBuffer with capacity 25 and print capacity

static void q2() {
StringBuffer sb = new StringBuffer(25);
System.out.println(sb.capacity()); // 25
}

Q3. Capacity of StringBuffer created from “Java”

static void q3() {
StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.capacity()); // 16 + 4 = 20
}

Q4. Show capacity growth formula (old*2)+2

static void q4() {
StringBuffer sb = new StringBuffer(); // capacity 16
sb.append("abcdefghijklmnop"); // 16 chars, full
System.out.println(sb.capacity()); // 16
sb.append("q"); // need more space
System.out.println(sb.capacity()); // becomes 34
}

Q5. Insert "JSE" at index 1 in "Hello"

static void q5() {
StringBuffer sb = new StringBuffer("Hello");
sb.insert(1, "JSE");
System.out.println(sb); // HJSEello
}

Q6. Reverse a StringBuffer "Hello"

static void q6() {
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // olleH
}

Q7. Compare time: StringBuilder vs StringBuffer (append)

static void q7() {
int iteration = 1_000_00; // 1 lakh
    long start = System.currentTimeMillis();
StringBuilder builder = new StringBuilder("Java");
for (int i = 0; i < iteration; i++) {
builder.append(" technology");
}
long end = System.currentTimeMillis();
System.out.println("Builder time: " + (end - start) + " ms");
start = System.currentTimeMillis();
StringBuffer buffer = new StringBuffer("Java");
for (int i = 0; i < iteration; i++) {
buffer.append(" technology");
}
end = System.currentTimeMillis();
System.out.println("Buffer time: " + (end - start) + " ms");
}

Q8. Reverse a string without using reverse()

static String q8(String str) {
String rev = "";
for (int i = str.length() - 1; i >= 0; i--) {
rev += str.charAt(i);
}
return rev;
}
// call: System.out.println(q8("RAJ")); // JAR

Q9. Reverse a string using StringBuilder

static String q9(String str) {
return new StringBuilder(str).reverse().toString();
}
// "Naresh" -> "hseraN"

Q10. Print duplicate characters and count them

static void q10(String str) {
char[] arr = str.toCharArray();
int count = 0;
    for (int i = 0; i < arr.length; i++) {
if (arr[i] == '\0') continue; // already counted
boolean duplicate = false;
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] == arr[j]) {
duplicate = true;
arr[j] = '\0'; // mark
}
}
if (duplicate) {
System.out.println("Duplicate char: " + arr[i]);
count++;
}
}
System.out.println("Total duplicate characters: " + count);
}

Q11. Remove all occurrences of a given character

static String q11(String str, char remove) {
StringBuilder result = new StringBuilder();
for (char c : str.toCharArray()) {
if (c != remove) {
result.append(c);
}
}
return result.toString();
}
// "ravi", 'v' -> "rai"

Q12. Check whether a string contains any vowel

static boolean q12(String str) {
str = str.toLowerCase();
for (char c : str.toCharArray()) {
if ("aeiou".indexOf(c) != -1) {
return true;
}
}
return false;
}
// "mango" -> true, "myths" -> false

Q13. Sort characters of a string (ascending)

static String q13(String str) {
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
for (int j = i + 1; j < ch.length; j++) {
if (ch[i] > ch[j]) {
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
}
}
}
return new String(ch);
}
// "mango" -> "agmno"

Q14. Count occurrences of a given character (case-insensitive)

static int q14(String str, char target) {
str = str.toLowerCase();
target = Character.toLowerCase(target);
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == target) count++;
}
return count;
}
// "Apple", 'p' -> 2

Q15. Check if a string contains any digits

static boolean q15(String str) {
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
return true;
}
}
return false;
}
// "Ravi123" -> true

Q16. Count uppercase and lowercase letters

static void q16(String str) {
int upper = 0, lower = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isUpperCase(ch)) upper++;
else if (Character.isLowerCase(ch)) lower++;
}
System.out.println("Uppercase letters: " + upper);
System.out.println("Lowercase letters: " + lower);
}

Q17. Count vowels and consonants

static void q17(String str) {
str = str.toLowerCase();
int vowels = 0, consonants = 0;
    for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z') {
if ("aeiou".indexOf(c) != -1) vowels++;
else consonants++;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}

Q18. Check if a string is palindrome

static boolean q18(String str) {
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
// "madam" -> true

Q19. Convert StringBuffer to String

static String q19() {
StringBuffer sb = new StringBuffer("NareshIT");
String s = sb.toString();
return s;
}

Q20. Convert StringBuilder to String

static String q20() {
StringBuilder sb = new StringBuilder("Java");
return sb.toString();
}

Q21. Create String from char array

static String q21() {
char[] ch = {'J', 'a', 'v', 'a'};
return new String(ch); // "Java"
}

Q22. Create String from byte array (ASCII values)

static String q22() {
byte[] b = {65, 66, 67}; // A, B, C
return new String(b); // "ABC"
}

Q23. Frequency of each character in a string

static void q23(String str) {
int[] freq = new int[256];
for (int i = 0; i < str.length(); i++) {
freq[str.charAt(i)]++;
}
for (int i = 0; i < freq.length; i++) {
if (freq[i] > 0) {
System.out.println((char) i + " -> " + freq[i]);
}
}
}

Q24. Remove duplicate characters (keep first occurrence)

static String q24(String str) {
boolean[] seen = new boolean[256];
StringBuilder result = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (!seen[c]) {
seen[c] = true;
result.append(c);
}
}
return result.toString();
}
// "banana" -> "ban"

Q25. Toggle case of each alphabet in a string

static String q25(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(Character.toLowerCase(c));
} else if (Character.isLowerCase(c)) {
sb.append(Character.toUpperCase(c));
} else {
sb.append(c); // keep as it is
}
}
return sb.toString();
}
// "JaVa123" -> "jAvA123"

--

--

Aman Verma
Aman Verma

Written by Aman Verma

📚#Software Engineer || Ai Technolgy || #ReadingIsLife || #techylife https://blog-project-one-silk.vercel.app/