String Methods
Java Strings are immutable objects with many built-in methods for manipulation.
Example
String text = "Hello, World!";
text.length(); // 13
text.charAt(0); // 'H'
text.substring(0, 5); // "Hello"
text.indexOf("World"); // 7
text.contains("World"); // true
text.replace("World", "Java"); // "Hello, Java!"
text.toLowerCase(); // "hello, world!"
text.toUpperCase(); // "HELLO, WORLD!"
text.trim(); // removes whitespace
text.split(", "); // ["Hello", "World!"]
text.isEmpty(); // false
text.isBlank(); // false (Java 11+) StringBuilder and Formatting
Use StringBuilder for efficient string concatenation in loops. Use String.format() or printf() for formatted output.
Example
// StringBuilder — mutable, efficient for building strings
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append("Item ").append(i).append(", ");
}
String result = sb.toString();
// String formatting
String name = "Alice";
int age = 25;
String msg = String.format("Name: %s, Age: %d", name, age);
System.out.printf("Price: $%.2f%n", 9.99);
// Text blocks (Java 15+)
String json = """
{
"name": "Alice",
"age": 25
}
"""; 