Explain the difference between string and string buffer class and also explain some method of string class with example.

Difference Between String and StringBuffer in Java (With String Methods and Examples)

1) Key Differences: String vs StringBuffer

  • Mutability:
    • String is immutable. Once created, its value cannot change. Any operation that looks like a modification actually creates a new String object.
    • StringBuffer is mutable. You can change its content in place using methods like append(), insert(), and delete().
  • Thread-safety:
    • String is inherently thread-safe due to immutability.
    • StringBuffer is thread-safe because its methods are synchronized, making it safe for multi-threaded use.
  • Performance:
    • Frequent concatenation with String is slower because it creates many temporary objects.
    • StringBuffer is faster for repeated modifications due to in-place updates. For single-threaded performance, developers often prefer StringBuilder (non-synchronized), but the question focuses on StringBuffer.
  • Memory behavior:
    • String literals can be stored in the String Pool and may be interned to avoid duplicates.
    • StringBuffer uses a resizable character array internally (on the heap) and does not use the String Pool.
  • Use cases:
    • Use String for fixed text, constants, and rarely changed data.
    • Use StringBuffer when building or modifying text repeatedly in multi-threaded environments.

2) Quick Code Illustration: Immutability vs Mutability

// String (immutable)
String s = "Java";
s.concat(" Rocks");           // A new String is created, but 's' still points to "Java"
System.out.println(s);        // Output: Java

// StringBuffer (mutable)
StringBuffer sb = new StringBuffer("Java");
sb.append(" Rocks");          // Modifies sb in place
System.out.println(sb);       // Output: Java Rocks

3) Common Methods of String Class (With Examples)

Below are frequently used String methods, with short explanations and simple examples to help you understand how they work.

a) length()

Returns the number of characters in the string.

String str = "Hello";
System.out.println(str.length()); // 5

b) charAt(int index)

Returns the character at the given index (0-based).

String str = "Hello";
System.out.println(str.charAt(1)); // 'e'

c) substring(int beginIndex) and substring(int beginIndex, int endIndex)

Extracts a part of the string. The end index is exclusive.

String str = "programming";
System.out.println(str.substring(3));      // "gramming"
System.out.println(str.substring(0, 7));   // "program"

d) indexOf(...) and lastIndexOf(...)

Finds the position of a character or substring. Returns -1 if not found.

String str = "banana";
System.out.println(str.indexOf('a'));         // 1
System.out.println(str.indexOf("na"));        // 2
System.out.println(str.lastIndexOf("na"));    // 4

e) equals(Object) and equalsIgnoreCase(String)

Checks content equality (case-sensitive or case-insensitive).

String a = "Java";
String b = "java";
System.out.println(a.equals(b));             // false
System.out.println(a.equalsIgnoreCase(b));   // true

f) compareTo(String) and compareToIgnoreCase(String)

Lexicographically compares two strings. Returns 0 if equal, positive/negative otherwise.

System.out.println("Apple".compareTo("Banana"));          // negative value
System.out.println("abc".compareToIgnoreCase("ABC"));     // 0

g) toUpperCase() and toLowerCase()

Converts the string to upper or lower case.

String str = "Hello World";
System.out.println(str.toUpperCase()); // "HELLO WORLD"
System.out.println(str.toLowerCase()); // "hello world"

h) trim()

Removes leading and trailing spaces (but not internal spaces).

String raw = "  BTech CSE  ";
System.out.println(raw.trim()); // "BTech CSE"

i) replace(char oldChar, char newChar) and replace(CharSequence, CharSequence)

Replaces characters or substrings (literal replacement).

String s = "cse-cse";
System.out.println(s.replace('c', 'C'));        // "Cse-Cse"
System.out.println(s.replace("cse", "CSE"));    // "CSE-CSE"

j) contains(CharSequence)

Checks whether a substring exists.

String s = "object oriented programming";
System.out.println(s.contains("oriented")); // true

k) startsWith(String) and endsWith(String)

Checks the prefix or suffix of the string.

String s = "datastructures.pdf";
System.out.println(s.startsWith("data")); // true
System.out.println(s.endsWith(".pdf"));   // true

l) split(String regex)

Splits a string around matches of the given regular expression.

String csv = "A,B,C";
String[] parts = csv.split(",");
System.out.println(parts.length);   // 3
System.out.println(parts[0]);       // "A"

m) valueOf(...) and String.valueOf(...)

Converts primitives and objects to their string representation.

int marks = 85;
String s = String.valueOf(marks);
System.out.println(s + " percent"); // "85 percent"

4) Extra: Useful StringBuffer Methods

  • append(...) – add text to the end
  • insert(int, ...) – insert text at a position
  • delete(int start, int end) – remove a range
  • reverse() – reverse the content
  • capacity() – current buffer capacity
StringBuffer sb = new StringBuffer("CSE");
sb.append(" Dept");             // "CSE Dept"
sb.insert(3, " -");             // "CSE - Dept"
sb.delete(4, 6);                // "CSE Dept"
sb.reverse();                   // "tpeD ESC"
System.out.println(sb);

5) Summary

  • String is immutable and ideal for fixed text and constants.
  • StringBuffer is mutable and synchronized, suitable for repeated changes in multi-threaded code.
  • Knowing common String methods helps in tasks like searching, slicing, formatting, and comparison.