String
- String is immutable unlike C++
- You cannot change the character in a string
- Also see immutable
Iteration
for(int i = 0, n = s.length() ; i < n ; i++) {
char c = s.charAt(i);
}- OR
for(char c : s.toCharArray()) {
// process c
}Stream
- Each element is string not character
List<String> characters = Arrays.asList(str.split(""));
str.split("").stream().....StringBuilder and StringBuffer
- https://www.baeldung.com/java-string-builder-string-buffer
- https://docs.oracle.com/javase/tutorial/java/data/buffers.html
- StringBuilder was introduced to replace StringBuffer
- Both can mutate the strings
- StringBuffer methods are synchronized and hence it is thread safe
- StringBuffer is slower than StringBuilder
StringBuilder sb = new StringBuilder("hello");
sb.append("world");
sb.toString();
StringBuffer sb = new StringBuffer("hello");
sb.append("world");
sb.toString();- StringBuilder and StringBuffer have same API contract
- API
reverse()append(input): input can be char, String, boolean, double, int, etc.- `insert(offset, input)
delete(start, end): start inclusive, end exclusivereplace(start, end, string): start inclusive, end exclusive
StringBuffer sb = new StringBuffer("I");
sb.append("Ron"); // IRon
sb.insert(1, " am "); // I am Ron
sb.delete(2, 5); // I Ron
sb.replace(1, 2, " play with "); // I play with Ron
sb.reverse();
System.out.println(sb.toString()); // noR htiw yalp I| String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Immutability | Immutable | Mutable | Mutable |
| Thread Safety | Not thread-safe | Not thread-safe | Thread-safe (synchronized methods) |
| Speed | Slow for frequent modifications/concatenations | Fastest | Slower than StringBuilder |
CharSequence
- It is an interface which String implements
- It does not enforce immutability or mutability
- It is implemented by
- String
- StringBuilder
- StringBuffer
Text Block
- https://docs.oracle.com/en/java/javase/17/text-blocks/index.html
- Introduced in Java 15+
- Uses triple double quotes
- opening triple double quotes must be followed by new line
// same as "red\ngreen\nblue\n"
String name = """
red
green
blue
""";
// same as "red\ngreen\nblue"
String name = """
red
green
blue""";- Incidental whitespace and essential whitespace
- least indentation is chosen as incidental whitespace
- incidental whitespace is deleted in the final String
- whitespace before first
<html>is incidental whitespace and determines left margin - indentation of
<body>relative to<html>is essential whitespace
/** same as
<html>
<body>
<p>Hello World.</p>
</body>
</html>
**/
String html = """
<html>
<body>
<p>Hello World.</p>
</body>
</html>
""";- Controlling left margin
- Last delimiter position can determine left margin
/** same as
red
green
blue
**/
String name = """
red
green
blue
""";
/** same as
red
green
blue
**/
String name = """
red
green
blue\
""";