Lesson 13: New String Methods in Java 11+ (strip(), lines(), repeat())

Java 11 introduced new methods for the String class, making it easier to handle whitespace, multi-line text, and string repetition.


1. strip(), stripLeading(), stripTrailing() (Better Whitespace Handling)

πŸ”Ή Before Java 11, trim() was used to remove spaces, but it only removed ASCII spaces (U+0020), not Unicode spaces.
πŸ”Ή Java 11 introduced strip(), which removes all leading and trailing Unicode whitespace.

MethodDescriptionExample
strip()Removes leading and trailing whitespace (Unicode-aware)" Hello ".strip() β†’ "Hello"
stripLeading()Removes leading whitespace only" Hello ".stripLeading() β†’ "Hello "
stripTrailing()Removes trailing whitespace only" Hello ".stripTrailing() β†’ " Hello"

πŸ“Œ Example 1: Difference Between trim() and strip()

public class Main {
    public static void main(String[] args) {
        String s1 = "   Hello   ";
        String s2 = "\u2003Hello\u2003"; // Unicode whitespace

        System.out.println("Trim: [" + s2.trim() + "]");  // Doesn't remove Unicode spaces
        System.out.println("Strip: [" + s2.strip() + "]"); // βœ… Removes Unicode spaces
    }
}

βœ… Output:

Trim: [ Hello ]
Strip: [Hello]

βœ” strip() removes Unicode whitespace, unlike trim().


πŸ“Œ Example 2: stripLeading() and stripTrailing()

public class Main {
    public static void main(String[] args) {
        String text = "   Java 11   ";

        System.out.println("Strip Leading: [" + text.stripLeading() + "]");
        System.out.println("Strip Trailing: [" + text.stripTrailing() + "]");
    }
}

βœ… Output:

Strip Leading: [Java 11   ]
Strip Trailing: [   Java 11]

βœ” More control over whitespace removal!


2. lines() – Splitting Multi-line Strings into a Stream

πŸ”Ή Before Java 11, splitting multi-line text required manually handling \n.
πŸ”Ή lines() simplifies this by converting a multi-line string into a Stream<String>.

πŸ“Œ Example: Using lines() to Process Multi-Line Text

import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String text = "Java 11\nNew Features\nImproved Performance";

        text.lines()
            .map(String::toUpperCase)  // Convert each line to uppercase
            .forEach(System.out::println);
    }
}

βœ… Output:

JAVA 11
NEW FEATURES
IMPROVED PERFORMANCE

βœ” lines() splits the string correctly without manually handling \n.


3. repeat(int n) – Repeat Strings Easily

πŸ”Ή Before Java 11, repeating a string required loops or StringBuilder.
πŸ”Ή repeat(n) simplifies this by repeating a string n times.

πŸ“Œ Example: Using repeat()

public class Main {
    public static void main(String[] args) {
        String star = "*";

        System.out.println(star.repeat(5)); // Prints ***** 
    }
}

βœ… Output:

*****

βœ” Simpler than using loops!


πŸ”„ Summary of Java 11+ String Methods

MethodPurposeExample
strip()Removes leading & trailing Unicode spaces" Hello ".strip() β†’ "Hello"
stripLeading()Removes only leading spaces" Hello ".stripLeading() β†’ "Hello "
stripTrailing()Removes only trailing spaces" Hello ".stripTrailing() β†’ " Hello"
lines()Splits multi-line text into a stream"A\nB".lines() β†’ Stream(["A", "B"])
repeat(n)Repeats the string n times"*".repeat(5) β†’ "*****"

Lesson Reflection

  1. Why is strip() better than trim() for removing whitespace?
  2. How does lines() make multi-line text processing easier?
  3. Can you think of a scenario where repeat() would be useful?

Answers to Reflection Questions on Java 11+ String Methods


1️⃣ Why is strip() better than trim() for removing whitespace?

βœ… strip() handles Unicode whitespace, while trim() does not.

  • trim() only removes ASCII space (U+0020).
  • strip() removes all Unicode whitespace characters (like \u2003 – an invisible space).

πŸ“Œ Example: Difference Between trim() and strip()

public class Main {
    public static void main(String[] args) {
        String unicodeSpace = "\u2003Hello\u2003"; // Unicode whitespace around "Hello"

        System.out.println("Trim: [" + unicodeSpace.trim() + "]");  // ❌ Doesn't remove Unicode spaces
        System.out.println("Strip: [" + unicodeSpace.strip() + "]"); // βœ… Removes Unicode spaces
    }
}

βœ… Output:

Trim: [ Hello ]  // ❌ Unicode spaces remain
Strip: [Hello]    // βœ… Unicode spaces removed

βœ” strip() is more powerful than trim() because it handles ALL whitespace characters.


2️⃣ How does lines() make multi-line text processing easier?

βœ… lines() splits multi-line strings into a Stream<String>, allowing functional processing.

  • Before Java 11, we had to manually split by \n and handle edge cases.
  • Now, lines() does the work automatically and ignores empty trailing lines.

πŸ“Œ Example: Processing Multi-Line Text with lines()

import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String text = "Java 11\nNew Features\nBetter Performance";

        text.lines()
            .map(String::toUpperCase)  // Convert each line to uppercase
            .forEach(System.out::println);
    }
}

βœ… Output:

JAVA 11
NEW FEATURES
BETTER PERFORMANCE

βœ” No need to manually split and loop over lines!


3️⃣ Can you think of a scenario where repeat() would be useful?

πŸš€ Yes! repeat(n) is useful when generating formatted output.

βœ… Use Case 1: Creating a Separator Line for Console Output

public class Main {
    public static void main(String[] args) {
        System.out.println("-".repeat(50)); // Prints a 50-character separator line
    }
}

βœ… Output:

--------------------------------------------------

βœ” This avoids loops or StringBuilder just to repeat characters.

βœ… Use Case 2: Generating Test Data

public class Main {
    public static void main(String[] args) {
        var sampleData = "ABC".repeat(5); // Repeats "ABC" 5 times
        System.out.println(sampleData);
    }
}

βœ… Output:

ABCABCABCABCABC

βœ” Great for quickly generating repeated patterns in testing.


πŸ” Key Takeaways

βœ” strip() is better than trim() because it removes all Unicode whitespace.
βœ” lines() simplifies multi-line text processing using Stream<String>.
βœ” repeat(n) eliminates the need for loops when generating repeated strings.

The next Java 11+ feature: New File Methods (readString(), writeString())? πŸ˜ŠπŸš€

Tags:

Java Sleep