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

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 exclusive
    • replace(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
StringStringBuilderStringBuffer
ImmutabilityImmutableMutableMutable
Thread SafetyNot thread-safeNot thread-safeThread-safe
(synchronized methods)
SpeedSlow for frequent
modifications/concatenations
FastestSlower 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

// 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\
  """;