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)
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);
Atul RaiAtul RaiAtul RaiAtul RaiAtul Rai
isBlank() method returns
true if a string is empty or only contains white space otherwise returns
String str2 = ""; System.out.println(str2.isBlank()); String str3 = " "; System.out.println(str3.isBlank()); String str4 = " Atul "; System.out.println(str4.isBlank());
true true false
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());
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());
Returns a string whose value is this string, with all trailing white space removed.
String str7 = "\t Manish \u2005"; System.out.println(str7.stripTrailing());
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);
No of lines: 3 [Hello I'm Atul Rai., I work for a MNC as SSE., And live in Sydney, Australia.]
- Core Java Interview Questions and Answers Part 4
- How to count the frequency of a character in a string in Java
- Send email with attachment in Java using Gmail
- How to set and get Thread name in Java
- How to Create Thread in Java