Core Java

Java 11 String Class New Methods Example

Photo of Gilbert LopezGilbert LopezMarch 7th, 2019Last Updated: March 12th, 2019
0 204 6 minutes read

In this example, we will discuss the new methods of the String class introduced in Java version 11.

1. Introduction

Every Java release comes with some new features.  Many of the features arise from inconsistencies of earlier releases.  Others are due to the ever-changing landscape of technology.  In this article, we will cover the new methods that were added to the String class in Java 11.  

  • String::strip
  • String::stripLeading
  • String::stripTrailing
  • String::isBlank
  • String::lines
  • String::repeat

1.4 Tools Used in this Example

  • Eclipse Java EE IDE for Java Developer 2018-12
  • Spring Tools 4 – for Spring Boot
  • Java 11.0.2

Spring Tools 4 for Spring Boot is a set of plugins for Eclipse that support building and running Spring Boot applications. You can add Spring Tools 4 to your existing Eclipse installation by going to the Eclipse Marketplace and searching for “Spring Tools 4”.

2. Java 11 String Class New Methods Example

2.1 Setup the Environment

Start by downloading the Java 11 JDK from the Oracle website.https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html

Next, follow the instructions in the Installation Guide from the Oracle Help Center.https://docs.oracle.com/en/java/javase/11/install/overview-jdk-installation.html#GUID-8677A77F-231A-40F7-98B9-1FD0B48C346A

To configure Java 11 in Eclipse, selectPreferencesfrom the menu and type “jre” in the search box.  SelectInstalled JREs from the result list.

Java 11 String Class New Methods - Java Runtime Environments
Installed Java Runtime Environments

Click on theAdd… button.  In theJRE Type dialog window, selectStandard VM and clickNext.

Java 11 String Class New Methods - JRE Type
JRE Type

Click on theDirectory… button and browse to the directory where you installed the Java 11 JDK. 

Java 11 String Class New Methods - Add JRE
Add JRE

ClickFinishandApply and Close.

2.2 Create a Spring Boot Project

Create a new Spring Boot starter project. 

Java 11 String Class New Methods - Spring Starter Project
New Spring Starter Project

Enter a project name.  In theJava Version drop-down menu select “11”.  Enter a Group, Artifact and Package name if desired and clickNext.  Since Spring Boot already includes the spring-boot-starter-test dependency we do not require any additional dependencies.  ClickFinish.

Java 11 String Class New Methods -  Spring Boot Project
New Spring Boot Project

2.3 Configure Spring Boot Project

An additional step is required to configure our project to use Java 11. Right-click the project and selectBuild Path > Configure Build Path. Select theLibrariestab. Remove the “J2SE-1.5 JRE” library and add the “jdk-11.0.2” library.

Java 11 String Class New Methods -  Add Alternate JRE
Add Alternate JRE

ClickFinishandApply and Close.

2.4 String::strip String::stripLeading and String::stripTrailing

Several new String methods were added because of the evolving
Unicode Standard.  Java uses Unicode,
which includes ASCII and other characters from languages around the world, for representing
characters.

In Java 11, character data is based on the Unicode Standard, version 10.0.0.  The Unicode specification includes some space characters (SPACE_SEPARATOR, LINE_SEPARATOR, and PARAGRAPH_SEPARATOR) that are not accounted for by theString::trim method.  To that end, the following methods have been added:

  • String::strip
  • String::stripLeading
  • String::stripTrailing

LikeString::trim, these methods remove white space from the beginning and end of a string. However, they are “Unicode-aware” and use the same definition that is used by theCharacter::isWhiteSpace method to resolve spaces. Let’s test these methods.

Right-click the Java package under/scr/test/java and selectNew > Other… JUnit Test Case.  ClickNext.  Enter “StripTest” for the test case name, select setUp() under “Which method stubs would you like to create” and clickFinish

Java 11 String Class New Methods -  JUnit Test Case
New JUnit Test Case

Add the following code to the StripTest class.

StripTest.java

import static org.junit.Assert.*;import org.junit.Before;import org.junit.Test;public class StripTest {String sWithWhiteSpace;@Beforepublic void setUp() throws Exception {sWithWhiteSpace = " 12\n\f";}@Testpublic void stripLeadingTest() {System.out.println("The String value is:" + sWithWhiteSpace.stripLeading());assertTrue("String does not match condition", sWithWhiteSpace.stripLeading().equals("12\n\f"));}@Testpublic void stripTrailingTest() {System.out.println("The String value is:" + sWithWhiteSpace.stripTrailing());assertTrue("String does not match condition", sWithWhiteSpace.stripTrailing().equals(" 12"));}@Testpublic void stripTest() {System.out.println("The String value is:" + sWithWhiteSpace.strip());assertTrue("String does not match condition", sWithWhiteSpace.strip().equals("12"));}}

We declare a String named “sWithWhiteSpace” as a class member.  We initialize it in the setup method with the value ” 12\n\f”.   Note that the string begins with a space and ends with the line feed and form feed control characters.

In the first test,stripLeadingTest, we strip the leading space with theString::stripLeading method and print out the result.  We then make an assertion that result does not have a leading space withassertTrue.

In the second test,stripTrailingTest, we strip the trailing space with theString::stripTrailing method and print out the result.  We then make an assertion that result does not have any trailing spaces withassertTrue.

In the final test,stripTest, we strip the leadingandtrailing spaces with theString::strip method and print out the result.  We then make an assertion that result does not have any leading or trailing spaces withassertTrue.

Right-click the class and selectRun As > JUnit Test. All tests should pass.

Java 11 String Class New Methods - JUnit Tests
JUnit Tests

You will also see the following output in the console.

JUnit Test Output

The String value is:12The String value is: 12The String value is:12

Note: You may see the form feed character as part of the output.

2.5 String::isBlank

Another new String method isString::isBlank.  It also uses the same definition that is used byCharacter::isWhiteSpace method to resolve spaces and returns true if the string is empty or contains only white space.  Create a new JUnit
test with the following code:

IsBlankTest.java

import static org.junit.Assert.*;import org.junit.Before;import org.junit.Test;public class IsBlankTest {String sTestForBlank;@Beforepublic void setUp() throws Exception {sTestForBlank = "\n";}@Testpublic void isBlankTest() {assertTrue("String is not blank", sTestForBlank.isBlank());}}

We declare a String named “sTestForBlank” as a class member.  We initialize it in the setup method with the value “\n”, the line feed control character.  In the test we call theisBlank method on the string an make an assertion that it is blank withassertTrue.

Right-click the class and selectRun As > JUnit Test. The test should pass.

2.6 String::lines

The introduction of Raw String Literals (expected in the Java version 12 release) will let the developer declare multi-line Strings without using escape characters.  In anticipation of this feature, theString::lines method was introduced, which will make it easier to process multi-line Strings.  TheString::lines method will split a multi-line string value into a stream of String objects delineated by end-of-line control characters.  Although you can achieve the same result by using theString::split method in conjunction with Java streams, theString::lines method is more convenient and efficient.

Create a new JUnit test with the following code:

LinesTest.java

import java.util.stream.Stream;import org.junit.Before;import org.junit.Test;public class LinesTest {String line1;String line2;String line3;String song;@Beforepublic void setUp() throws Exception {line1 = "Love, Love me do.";line2 = "You know I love you.";line3 = "I'll always be true.";song = line1 + System.lineSeparator() + line2 + System.lineSeparator() + line3;}@Testpublic void testLines() {Stream lines = song.lines();;lines.forEach(System.out::println);}}

We declare four Strings as class members.  We initialize lines 1-3 and concatenate the lines in the song variable in the setup method.  In thetestLines method, we create aStream of strings using theString::lines method and iterate over the stream, printing them out to the console.

Right-click the class and selectRun As > JUnit Test. The output will appear as follows:

JUnit Test Output

Love, Love me do.You know I love you.I'll always be true.

2.7 String::repeat

The last new String method we will look at is theString::repeat method.  You may want to use this method to create headers and comments or for testing purposes.  The method takes an int “x” as a parameter and repeats the string “x” number of times. Here is an example.

RepeatTest.java

import org.junit.Before;import org.junit.Test;public class RepeatTest {String flowerText;@Beforepublic void setUp() throws Exception {flowerText = "This is a Flower Box.";}@Testpublic void testRepeat() {String flowers = "*".repeat(flowerText.length() + 6);System.out.println("\n" + flowers);System.out.println("** " + flowerText + " **");System.out.println(flowers);}}

Right-click the class and selectRun As > JUnit Test. The output will appear as follows:

JUnit Test Output

***************************** This is a Flower Box. *****************************

3. Java 11 String Class New Methods – Summary

In this example, we discussed and tested the new methods of the String class introduced in Java version 11.

4. Download the Source Code

This was a Java 11 String Class New Methods Example.

Download
You can download the full source code of this example here: Java 11 String Class New Methods Example
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Tags
Photo of Gilbert LopezGilbert LopezMarch 7th, 2019Last Updated: March 12th, 2019
0 204 6 minutes read
Photo of Gilbert Lopez

Gilbert Lopez

Gilbert Lopez is an application developer and systems integration developer with experience building business solutions for large and medium-sized companies. He has worked on many Java EE projects. His roles have included lead developer, systems analyst, business analyst and consultant. Gilbert graduated from California State University in Los Angeles with a Bachelor of Science degree in Business.

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.