Java 11 new features and Enhancements : API Changes

The world is moving fast, so as the changes in the java technology. We saw the release of java 10 in March 2018. Fast forward 6 months we have the release of java 11. Java 11 released in September 2018. As expected, with every new version of java, some features are added and some are deprecated. In this article we will look into the java 11 new features and enhancements that include String API new methods isBlank(), strip(), lines(), repeat() etc. We will also take a look at File API, Collection changes and other features. 

Read Also :  Frequently Asked Java 8 Interview Questions

1. String API

String class is the most heavily used java class in the tech industry. In the java 11, Oracle has added few useful methods to the String API class.

1.1 String.repeat() method

The name of the method is sufficient to know what this method does.You guess it right, It will repeat the string content.

The method signature of repeat() method is

public String repeat(int count)

where count parameter represents number of times the same string is concatenated.

Example :

var tempString = "Java Hungry "; 
 
var repeatString = tempString.repeat(2);// count parameter value is 2 
 
System.out.println(repeatString);//Output : Java Hungry Java Hungry


What happens if count parameter value is 0 or we do not pass any parameter to the  String repeat method.

According to Oracle docs,

If the string is empty or count is zero then the empty string is returned by the repeat() method.

Example : When parameter passed is 0


String tempString = "Java Hungry "; 
 
String repeatString = tempString.repeat(0);// count parameter value is 0 
 
System.out.println(repeatString); // Output : "" (Empty String)


Example : When string to repeat is empty


String tempString = ""; // empty String 
 
String repeatString = tempString.repeat(2); 
 
System.out.println(repeatString); // Output : "" (Empty String)


What happens if we pass negative value as a parameter

String tempString = "Java Hungry"; 
 
String repeatString = tempString.repeat(-1);// It will throw 
                                               IllegalArgumentException

Output :
IllegalArgumentException

1.2 String.strip() method ,stripLeading() method, stripTrailing() method


String.strip() method : returns a String with all leading and trailing white space removed.

String.stripLeading() method : returns a String with all leading white space removed.

String stripTrailing() method : returns a String with all trailing white space removed.

Example :

"  JavaHungry  ".strip().equals("JavaHungry");// Output : true 
 
"   JavaHungry".stripLeading().equals("JavaHungry");// Output : true 
 
"JavaHungry    ".stripTrailing().equals("JavaHungry");// Output : true


If we call strip() method on an empty String or if all code points in the String are white space, then an empty String is returned.

Otherwise, returns a substring of this string beginning with the first code point that is not a white space up to and including the last code point that is not a white space.


1.3 Difference between strip() and trim() method in java

trim() method exists before the Unicode was fully evolved. So, the definition of white space used by the String.trim() method is any code point less than or equal to the space code point ("\u0020") also called as ASCII or ISO control characters.

Example

("\n\n\t  javahungry   \u2005".trim()).equals("javahungry   \u2005");

Output : not able to remove the trailing white spaces.
This is because trim() does not have idea of unicode characters. As a result, it does not consider "\u2005" as white space character.

("\n\n\t  javahungry   \u2005".strip()).equals("javahungry   \u2005");

Output : both leading and trailing spaces are removed

1.4 isBlank() method

public boolean isBlank() : isBlank() returns true if the string contains only white space codepoints or is empty. For any other conditions, it return false.

Example

String blankString = " ".isBlank() // Output : true

isBlank() can recognize unicode characters just like strip() method do.

1.5 lines() method

Returns a stream of lines extracted from the input 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).

A line is either a sequence of zero or more characters followed by a line terminator, or it is a sequence of one or more characters followed by the end of the string. A line does not include the line terminator.

The stream returned by this method contains the lines from the input string in the order in which they occur.

Implementation :

lines() method should be preferred over split("\R") method as it provides better performance  by supplying elements lazily and by faster search of new line terminators.

Example :

"java\nhungry\nblog".lines().forEach(System.out::println);

Output:

java
hungry
blog

2. Collection Changes

2.1 Collections.toArray(IntFunction) Default Method 

A new Default method toArray(IntFunction) has been added to the Java Collection Interface. This method returns an Array containing all of the elements in the Collection.
This method acts as a bridge between collection-based and array-based APIs. It allows creation of an array of a particular runtime type.

final Set fruits = Set.of("Apple", "Mango", "Banana", "Orange"); 
 
out.println(Arrays.toString(fruits.toArray(String[]::new)));

Output :
[Banana, Orange, Apple, Mango]

3. Java.nio.file.Files API

3.1 readString() :

This method reads all content from a file into a String. Using UTF-8 charset it decodes from bytes to characters. This function makes sure that the file is closed when all content have been read or an I/O Error or other runtime exception, is thrown.

jshell>Files.readString(Path.of(readFile.txt));

Output :
"JavaHungry"

3.2 writeString() :

This method writes a CharSequence to a file. Using the UTF-8 charset Characters are encoded into bytes.

jshell>Files.writeString(Path.of(writeFile.txt), "JavaHungry");


There is another overloaded method of writeString() which is introduced in java 11. The method signature of overloaded writeString method is

writeString(Path path, CharSequence csq, Charset cs, OpenOption... options)

4. java.io 

In some situtations we use functions that require Reader/Writer/InputStream/OutputStream parameter and we want to process the parameter even if it represents a null.

Initializing the stream with null is not possible prior to  java 11. If you try to do so, then it will throw NullPointerException.

Below are the new methods which have been added to return streams that represent disabled input/output. They do not read anything and discard all writes.

public static InputStream nullInputStream() // java.io.InputStream class 
 
public static OutputStream nullOutputStream() // java.io.OutputStream class
 
public static Reader nullReader() // java.io.Reader class
 
public static Writer nullWriter() // java.io.Writer class


Code Example:

Reader readerObj = Reader.nullReader(); // Do not read anything
Writer writerObj = Writer.nullWriter(); // Discard write


5. java.nio.file.Path API  

Two overloaded methods have been added in java 11. Both Overloaded method create a Path instance

5.1 static Path of(String first, String… more)

This method returns a Path by converting a sequence of strings that when joined form a Path String. If more value is not specified then the first parameter value is the path string to convert.

Path path = Path.of("C:", "temp", "javahungry.txt"); 
 
System.out.println(Files.exists(path) + " " + path);

Output :
true C:\temp\javahungry.txt

5.2 static Path of(URI uri)

This method returns a Path by converting a URI.

URI uri = URI.create("file:///C:/temp/javahungry.txt");
System.out.println(uri);

Output :
file:///C:/temp/javahungry.txt

6. java.lang.Class  API

Below methods have been introduced in the java.lang.Class

6.1 public Class getNestHost()

This method returns the nested host.

6.2 public boolean isNestmateOf(Class c)

This method determines if the given Class is a nestmate of the class or interface represented by the Class object parameter.

6.3 public Class[]  getNestMembers()

This method returns all members of the nest this class belongs to.

That's all for the java 11 new features and enhancements. I have shared most of the API changes introduced in the java 11. If you know any other API changes that have not been covered in this post but are introduced in the java 11 then please let me know in comments. I will add it to this post.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry