Java
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
By EZ4Code Team
stringbeginner
Code
public class StringDemo {
public static void main(String[] args) {
String s = "Hello, World";
System.out.println(s.length());
System.out.println(s.substring(0, 5)); // Hello
System.out.println(s.charAt(7)); // W
String[] parts = s.split(", ");
String joined = String.join(" | ", parts);
boolean has = s.contains("World");
int idx = s.indexOf("o");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) sb.append(i);
System.out.println(sb); // 012
String json = """
{"name": "Alice"}
""";
System.out.println(json);
}
}Explanation
Covers common String methods (length, substring, charAt, split, join, contains, indexOf) and StringBuilder for efficient concatenation in loops. Strings are immutable in Java, so StringBuilder avoids creating intermediate objects. Java 15+ text blocks (""") simplify multi-line string literals like JSON or SQL.
More Java Snippets
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.
File IO
Read and write file operations.