Java Strings and StringBuilder
1. String Creation in Java
String can be created in two ways:
1. Using String Literal:
String s1 = "Hello";
2. Using new keyword:
String s2 = new String("Hello");
Strings are immutable - once created, they cannot be changed.
2. Common String Methods
- length() -> Returns number of characters
- charAt(int) -> Character at index
- substring(a, b) -> Substring from a to b-1
- equals(), equalsIgnoreCase() -> String comparisons
- toLowerCase(), toUpperCase() -> Case conversions
- contains(String) -> Check if substring exists
- startsWith(), endsWith() -> Check prefix/suffix
- indexOf(), lastIndexOf() -> Index of char/substring
- replace(), replaceAll() -> Replace characters/strings
- trim() -> Removes spaces from start/end
- split(regex) -> Splits string into array
- isEmpty() -> Checks if string is empty
- compareTo() -> Lexicographic comparison
- format() -> Formatted output (like printf)
- join(), repeat() -> Joining and repeating strings (Java 8+/11+)
3. Iterating Over Characters in a String
Java Strings and StringBuilder
Using for loop:
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
System.out.println(ch);
}
Using for-each with toCharArray():
for (char ch : s.toCharArray()) {
System.out.println(ch);
}
4. StringBuilder in Java
StringBuilder is mutable and used for efficient string manipulation.
Creating:
StringBuilder sb = new StringBuilder("Hello");
Common Methods:
- append(String) -> Add to end
- insert(index, str) -> Insert at index
- replace(a, b, str) -> Replace from a to b-1
- delete(a, b) -> Delete from a to b-1
- reverse() -> Reverse the string
- setCharAt(i, ch) -> Set char at index
- charAt(i) -> Get char at index
- length() -> Get length
- toString() -> Convert to String
Java Strings and StringBuilder
StringBuilder is faster than String when many changes are needed.