Cool new methods added to String in Java

Pradeesh Kumar
5 min readJan 5, 2023

Introduction

The String is one of the most commonly used types in every general-purpose programming language. That’s why string is treated with the most attention in Java. In each release of Java, there will be substantial changes dedicated to the String. This article covers the cool new important enhancements made to the String in Java.

1. lines

Java 11: The method Stream<String> lines()returns a stream of lines extracted from this string, that was separated by line terminators.

String sentence = "marry\n had\n a\n little\n lamb";
Stream<String> lineStream = sentence.lines();
lineStream.forEach(System.out::println); // Prints as below
// marry
// had
// a
// little
// lamb

System.out.println("The sentence has a total of " + sentence.lines().count() + " lines"); // The sentence has a total of 5 lines

2. repeat

Java 11: The method String repeat(int numberOfTimes)returns a String composed of the concatenation of the original string repeated the specified number of times.

System.out.println("java".repeat(5));    // javajavajavajavajava
System.out.println("apple, ".repeat(4)); //apple, apple, apple, apple,
System.out.println("*".repeat(10)); // **********

3. formatted

Java 15: The method String formatted(Object... args) returns a formatted string with the given arguments.

String msg = "Your name is %s and Your age is %d".formatted("Nick", 18);
System.out.println(msg); // Your name is Nick and Your age is 18

Java also provides a static method String String.format(String format, Object... args)

String fmt = "Your name is %s and Your age is %d";
String msg = String.format(fmt, "Nick", 18);
System.out.println(msg); // Your name is Nick and Your age is 18

4. indent

Java 12: The method String indent(int n) adjusts the indentation of each line of this string with the specified number of spaces.

String poem = "Two loves I have of comfort and despair,\n" +
"Which like two spirits do suggest me still:\n" +
"The better angel is a man right fair,\n" +
"The worser spirit a woman color’d ill.\n";

System.out.println(poem);
System.out.println(poem.indent(4));
System.out.println(poem.indent(10));

Output:

Two loves I have of comfort and despair,
Which like two spirits do suggest me still:
The better angel is a man right fair,
The worser spirit a woman colord ill.

Two loves I have of comfort and despair,
Which like two spirits do suggest me still:
The better angel is a man right fair,
The worser spirit a woman colord ill.

Two loves I have of comfort and despair,
Which like two spirits do suggest me still:
The better angel is a man right fair,
The worser spirit a woman colord ill.

5. Text block or Multiline String

Java 15: The Text block feature provides a new way to create a multi-line string in Java without concatenations and escape sequences. Java introduced triple quotation enclosed Strings to achieve this. Click here to know more.

// Old way
String html = "<html>\n" +
" <body>\n" +
" <p>Hello World</p>\n" +
" </body>\n" +
"</html>\n";
// This is neat
String html = """
<html>
<body>
<p>Hello World</p>
</body>
</html>
""";

6. transform

Java 12: The method <R> R transform(Function<? super String, ? extends R> f)applies the given function to this string. The function should expect a single String argument and produce an R result.

Function<String, String> titleCase = s -> Character.toUpperCase(s.charAt(0)) + s.toLowerCase().substring(1);
System.out.println("animal".transform(titleCase)); // Animal

Function<String, Integer> converToInt = Integer::parseInt;
int num = "123".transform(converToInt);
System.out.println(num); // 123

7. join

Java 8: The static methodjoin helps us to concatenate a list of CharSequences separated by a delimiter. There are two overloaded join methods:

a). String join(CharSequence delimiter, CharSequence... elements)

Returns a new String composed of the elements joined together and separated by the delimiter.

String joined = String.join("-", "java", "programming", "hello", "world");
System.out.println(joined); // Output: java-programming-hello-world

String joined2 = String.join("", "java", "programming", "hello", "world");
System.out.println(joined2); // Output: javaprogramminghelloworld

b). String join(CharSequence Iterable<? extends CharSequence> elements)

Returns a new String composed of elements from the iterable joined together and separated by the delimiter. This is useful when you want to pass a Collection object such as List, Set etc.

List<String> list = List.of("java", "programming", "hello", "world");
String joined = String.join(", ", list);
System.out.println(joined); // Output: java, programming, hello, world

8. translateEscapes

Java 15: The method String translateEscapes() returns a new String with escape sequences translated if present in the original string.

String s = "java\\nhello\\tword";
System.out.println(s); // Output: java\nhello\tword

System.out.println(s.translateEscapes());
// Output:
// java
// hello word

9. isBlank

Java 11: The method boolean isBlank() Returns true if the string is empty or contains only white space. A white space can be a space, line separator, tabs, form feed character etc.

System.out.println("    ".isBlank());          // true
System.out.println(" ".isEmpty()); // false

System.out.println("".isBlank()); // true
System.out.println("".isEmpty()); // true

System.out.println("\n".isBlank()); // true
System.out.println("\t".isBlank()); // true
System.out.println(" hello ".isBlank()); // false

10. strip

Java 11: The method String strip() returns a new string by removing both the leading and trailing white spaces from the original string. Remember, Java had the method String trim() to do the same functionality. However, thetrim works only with ASCII characters, whereas strip works for both ASCII, Unicode and everything.

System.out.println("   hello world!    ".strip()); // hello world!

Java also added two additional methods stripLeading and stripTrailing which are used to strip only leading white spaces and trailing white spaces respectively.

System.out.println("   hello world    ".stripLeading()); // hello world
System.out.println(" hello world ".stripTrailing()); // hello world

11. chars

Java 9: The method chars() returns a stream of int of character code values of the given String.

String word = "hello";
word.chars().forEach(System.out::println); // 104, 101, 108, 108, 111

12. codePoints

Java 9: The methodIntStream codePoints returns a stream of int of Unicode code points of the String.

String word = "hello";
word.codePoints().forEach(System.out::println); // 104, 101, 108, 108, 111

Java also added four additional methods related to the Unicode code points:

int codePointAt(int index) : Returns the Unicode point at the specified index.

int codePointBefore(int index) : Returns the Unicode point previous to the specified index.

int codePointAt(int index) : Returns the number of Unicode points in the specified text range.

13. describeConstable

The method Optional<String> describeConstable()returns an Optional containing the nominal descriptor for the given string, which is the string itself.

String s = "Java";
Optional<String> optionalS = s.describeConstable();
System.out.println(optionalS.get());

14. resolveConstantDesc

The methodString resolveConstantDesc(Lookup lookup)resolves the given string as ConstantDesc and returns the string itself.

System.out.println("Java".resolveConstantDesc(MethodHandles.lookup()));

--

--

Pradeesh Kumar

Computer Science | Distributed Computing | Databases | Cloud