New Incoming String Methods with JDK 11

As you know, there are lot’s of change from JDK 8 to JDK 11. I want to show new incoming String methods with examples. I suggest that you should try to run shared codes without IDE. If you don’t know how to run java application in command line, you can check out “How to Compile and Run Java Program from Command Line” that I had explained before.

Additionally, with Java 11, a major change in this version is that we don’t need to compile the Java source files with javac explicitly anymore so we don’t need to run javac command, only java command enough.

New String Methods

  • repeat(int):String
  • lines():Stream<String>
  • strip():String
  • stripLeading():String
  • stringTrailing():String
  • isBlank():boolean

Let’s look up how they are working.

repeat(int):String

A string whose value is the concatenation of this string repeated count times, If the string is empty, it returns empty.

CLI Outputs :

Scenario-1
Before=[Hello World!]
After=[Hello World!Hello World!Hello World!]
Scenario-2
Before=[]
After=[]
Scenario-3
Before=[ Contain-Space ]
After=[ Contain-Space Contain-Space Contain-Space ]

lines():Stream<String>

I think own description’s very clear. Returns a stream of lines extracted from this string, separated by line terminators. A line terminator is one of the following: a line feed character “\n” (U+000A), a carriage return character “\r” (U+000D), or a carriage return followed immediately by a line feed “\r\n” (U+000D U+000A).

CLI Output :

Scenario-1
Hello World!
Scenario-2
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Scenario-3
Blue
White
Green
Black
Yellow
Scenario-4
[One]
[Two]
[Three]
[Four]
[Five]

strip():String

Removes the white space from both, beginning and the end of string. It looks like similar with trim(). doesn’t it ? In fact, trim() removes only characters <= U+0020 (space); strip() removes all Unicode whitespace characters.

CLI Output :

Scenario-1
[Hello World!]
Scenario-2
Before=[ Jack William ]
AfterStrip=[Jack William]
AfterTrim=[ Jack William ]

stripLeading():String

Removes the white space from beginning of string.

CLI Output :

Scenario 1
[Hello World! ]
Scenario 2
Before=[ BreakingBad ]
AfterStripLeading=[BreakingBad ]

stripTrailing():String

Removes the white space from end of string.

CLI Output :

Scenario 1
[ Hello World!]
Scenario 2
Before=[ John ]
After=[ John]

isBlank():boolean

Returns true if the string is empty or contains only white space, otherwise false.

CLI Output :

Scenario 1
false
Scenario 2
true
Scenario 3
true

I hope everything is clear for you. If you don’t understand any part, Please feel free, ask me.

I indicated resources that I used for prepare this essay in the following. You can check out.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store