Java 11- New Methods of String Class
Java 11 (JDK 11) added a few new utility methods in the String class. These utility methods will reduce the complexity of the program and improve code readability and performance.
- repeat(int count)
- isBlank()
- strip()
- stripLeading()
- stripTrailing()
- lines()
1. repeat(int count)
repeate(int count)
method repeats the string ‘n’ times (concatenate the string) and returns a string composed of this string repeated ‘n’ times. It will throw IllegalArgumentException
if the count is negative.
String str1 = "Atul Rai";
String result1 = str1.repeat(5);
System.out.println(result1);
Output:
Atul RaiAtul RaiAtul RaiAtul RaiAtul Rai
2. isBlank()
isBlank()
method returns true
if a string is empty or only contains white space otherwise returns false
.
String str2 = "";
System.out.println(str2.isBlank());
String str3 = " ";
System.out.println(str3.isBlank());
String str4 = " Atul ";
System.out.println(str4.isBlank());
Output:
true
true
false
3. strip()
The strip()
method removed all the leading and trailing white space and return a new composed string.
String str5 = "\t Manish \u2005";
System.out.println(str5.strip());
Output:
Manish
4. stripLeading()
stringLeading()
method returns a string whose value is this string, with all leading white space removed.
String str6 = "\t Manish \u2005";
System.out.println(str6.stripLeading());
Output:
Manish #
5. stripTrailing()
Returns a string whose value is this string, with all trailing white space removed.
String str7 = "\t Manish \u2005";
System.out.println(str7.stripTrailing());
Output:
Manish
6. lines()
lines()
method returns a stream of lines extracted from this string, separated by line terminators such as \r, \n.
String str8 = "Hello I'm Atul Rai.\nI work for a MNC as SSE.\rAnd live in Sydney, Australia.";
long lineCount = str8.lines().count();
System.out.println("No of lines: " + lineCount);
List<String> lines = str8.lines().collect(Collectors.toList());
System.out.println(lines);
Output:
No of lines: 3
[Hello I'm Atul Rai., I work for a MNC as SSE., And live in Sydney, Australia.]