String Handling in Java
Understanding String Manipulation
and Operations
Introduction to Strings
• • Strings in Java are sequences of characters.
• • Implemented using the String class in
java.lang package.
• • Strings are immutable in Java.
• • Java provides StringBuffer and StringBuilder
for mutable strings.
String Class & Methods
• • Important methods in String class:
• - length()
• - charAt(index)
• - substring(start, end)
• - toLowerCase(), toUpperCase()
• - trim(), replace(old, new)
• - split(regex), concat(str)
StringBuffer & StringBuilder
• • StringBuffer: Mutable and thread-safe.
• • StringBuilder: Mutable but not thread-safe
(faster).
• • Important methods:
• - append(str), insert(offset, str)
• - replace(start, end, str), delete(start, end)
• - reverse(), capacity(), ensureCapacity(n)
String Manipulation Examples
• Example 1: Concatenation
• String s1 = "Hello";
• String s2 = " World!";
• String result = s1 + s2;
• System.out.println(result);
• Example 2: StringBuilder usage
• StringBuilder sb = new StringBuilder("Java");
• sb.append(" Programming");
Important String Operations
• • Comparing Strings: equals(), compareTo()
• • Searching: indexOf(), lastIndexOf()
• • Extracting: substring(start, end)
• • Splitting and Joining: split(), join()
• • Formatting: format(), valueOf()