String Handling
String Handling
String handling in Java refers to the manipulation, creation, and manipulation of strings, which
are sequences of characters. In Java, strings are represented by the java.lang.String class. Java
provides a rich set of methods and features for working with strings.
String Methods: Java provides numerous methods for performing operations on strings, such as:
length(): Returns the length of the string.
charAt(int index): Returns the character at the specified index.
substring(int beginIndex, int endIndex): Returns a substring of the original string.
indexOf(String str): Returns the index of the first occurrence of the specified substring.
toUpperCase() / toLowerCase(): Converts the string to uppercase or lowercase.
split(String regex): Splits the string into an array of substrings based on the specified regular
expression.
String Comparison: You can compare strings in Java using the equals() method for content
comparison and the compareTo() method for lexicographical comparison.
String str3 = "hello";
String str4 = "Hello";
boolean isEqual = str3.equals(str4); // Content comparison
int compareResult = str3.compareTo(str4); // Lexicographical comparison
String Immutability: Strings in Java are immutable, meaning their values cannot be changed
once they are created. Operations on strings return new string objects rather than modifying the
original string.
String Formatting: Java provides the String.format() method and the printf() method (from
PrintStream and PrintWriter classes) for formatting strings.
String formattedString = String.format("Name: %s, Age: %d", "John", 30);
System.out.printf("Name: %s, Age: %d%n", "John", 30);
StringBuilder and StringBuffer: For mutable string manipulation, Java provides StringBuilder
and StringBuffer classes. These classes are used when frequent modifications to strings are
required.
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" World");
String result = sb.toString(); // Convert StringBuilder to String
String handling is fundamental in Java programming, and understanding its concepts and
methods is acrucial for developing Java applications effectively.