0% found this document useful (0 votes)
26 views

Java 11 Features @pankaj

Uploaded by

tmdjgs7zjq
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Java 11 Features @pankaj

Uploaded by

tmdjgs7zjq
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

@Pankaj Kumar

Java 11 Features
——————————
1. Importance of Java 11.
2.Running Java File with single command.
3.Java String Method.
4.Local-Variable Syntax for Lambda Parameters.
5.Nested based Access Control.
6.Dynamic class-file Constants
7.Epsilon: A No-Op Garbage Collector
8.Remove the Java EE and CORBA Modules
9.Flight Recorder
10.HTTP Client API
11. Reading/Writing String to and from the Files.
12.ChaCha20 and Poly 1305 Cryptographic Algorithms
13.Improve Aarch64 Intrinsics.
14.ZGC: A Scalable Low-Latency Garbage Collector
15. Deprecate the Nashorn JavaScript Engine

 1. Why is Java 11 important?

 - Java 11 is the second LTS release after Java 8.


 - This way you’ll get all the updates and support for Java 11 till 2026.

Java 11 Features.

2) Running Java File with single command


One major change is that you don’t need to compile the java source file with
javac tool first. You can directly run the file with java command and it implicitly
compiles.
Before java 11- for compile java file we are writing in command
Javac filename.java
Java class name -> output…

Now from java 11


Java fileName -> output…

3) Java String Methods


isBlank(),lines(),Strip(),stripLeading(), stripTrailing(), trim(), repeat().

isBlank() – This instance method returns a boolean value. Empty Strings and
Strings with only white spaces are treated as blank.
import java.util.*;

public class Main {


public static void main(String[] args) throws Exception {
// Your code here!

System.out.println(" ".isBlank()); //true

String s = "Anupam";
System.out.println(s.isBlank()); //false
String s1 = "";
System.out.println(s1.isBlank()); //true
}
}

lines()-> This method returns a stream of strings, which is a collection of all


substrings split by lines.
import java.util.stream.Collectors;

public class Main {


public static void main(String[] args) throws Exception {

String str = "JD\nJD\nJD";


System.out.println(str);
System.out.println(str.lines().collect(Collectors.toList()));
}
}
Output;-

JD
JD
JD
[JD, JD, JD]

strip(), stripLeading(), stripTrailing() method


strip() method removes all leading and trailing white space and returns a new string.
stripLeading() method - Returns a new string with all leading white spaces is removed.
stripTrailing() method - Used to remove white spaces only at the ending of a string.

An example using the above three methods is given below:

public class Main {


public static void main(String[] args) throws Exception {
// Your code here!

String str = " JD ";


System.out.print("Start");
System.out.print(str.strip());
System.out.println("End");

System.out.print("Start");
System.out.print(str.stripLeading());
System.out.println("End");

System.out.print("Start");
System.out.print(str.stripTrailing());
System.out.println("End");
}
}
The output in the console from the above code is:

StartJDEnd
StartJD End
Start JDEnd

repeat(int)
The repeat method simply repeats the string that many numbers of times as mentioned in the method in
the form of an int.
public class Main {
public static void main(String[] args) throws Exception {
// Your code here!

String str = "=".repeat(2);


System.out.println(str); //prints ==
}
}

4.Local-Variable Syntax for Lambda Parameters.

Local-Variable Syntax for Lambda Parameters is the only language feature release in Java 11

to be used to declare the formal parameters of an implicitly typed lambda expression.


We can now define :

(var s1, var s2) -> s1 + s2


(var s1, s2) -> s1 + s2 //no skipping allowed
(var s1, String y) -> s1 + y //no mixing allowed

var s1 -> s1 //not allowed. Need parentheses if you use


var in lambda.

s1 -> s1.toUpperCase()
we cannot skip them while using var:
var s1 -> s1.toUpperCase()

5.Nested based Access Control.

Java 11 introduced nest-based access control that allows classes


to access each other's private members without the need for
bridge methods.

public class Main {

private void display() {


System.out.println("hello from private method");
}

class NestedMain{
void msg() {
display();
}
}

public static void main(String[] args){

Main m = new Main();


Main.NestedMain n = m.new NestedMain();
n.msg();

}
}

Output:-
hello from private method

6.Dynamic class-file Constants

Extend the Java class-file format to support a new constant-pool form, CONSTANT_Dynamic. Loading
a CONSTANT_Dynamic will delegate creation to a bootstrap method, just as linking an invoked
dynamic call site delegates linkage to a bootstrap method.

Future work
Possible future extensions include:
 Support for bulk-scale constants such as arrays or resource tables
 Further adjustments to the bootstrap-method handshake
 Other uses of bootstrap methods which may synergise with dynamic
constants
 Attaching dynamic constants to the ConstantValue attribute of static
fields
 Surfacing the lazy initialisation of constants in the Java language
 Integrating new constants with special Java language rules for constant
expressions
A discussion of design choices can be found in jdk 8 which deals with a
number of related RFEs. The present JEP was distilled from this larger list of
features.

7.Epsilon: A No-Op Garbage Colector


JVM GC which is responsible for allocating memory and releasing it, Epsilon
only allocates memory.
It allocates memory for the following things:
 Performance testing.
 Memory pressure testing.
 VM interface testing.
 Extremely short lived jobs.
 Last-drop latency improvements.
 Last-drop throughput improvements.

Now Elipson is good only for test environments. It will lead to


OutOfMemoryError in production and crash the applications.
The benefit of Elipson is no memory clearance overhead. Hence it’ll give an
accurate test result of performance and we can no longer GC for stopping it.
Note: This is an experimental feature.

8.Remove the Java EE and CORBA Modules

The modules were already deprecated in Java 9. They are now completely
removed.
Following packages are removed:
Name Module Description
Java API for XML Web java.xml.ws Defines the Java API for XML-Based Web
Services (JAX-WS) Services (JAX-WS), and the Web Services
Metadata API.
jdk.xml.ws Tools for JAX-WS
Java Architecture for XML java.xml.bind Defines the Java Architecture for XML Binding
Binding (JAXB) (JAXB) API.
jdk.xml.bind Tools for JAXB
JavaBeans Activation Defines the JavaBeans Activation Framework
java.activation
Framework (JAF) (JAF) API.
Common Annotations java.xml.ws.ann Defines a subset of the Common Annotations
otation API to support programs running on the Java
SE Platform.
Common Object Request
Defines the Java binding of the OMG CORBA
Broker Architecture java.corba
APIs, and the RMI-IIOP API.
(CORBA)
Java Transaction API java.transaction Defines a subset of the Java Transaction API
(JTA) (JTA) to support CORBA interoperation.
Aggregator module for the java.se.ee Defines the full API of the Java SE Platform.
all modules above

9.Flight Recorder

Flight Recorder which earlier used to be a commercial add-on in Oracle JDK


is now open-sourced since Oracle JDK is itself not free anymore.
JFR is a profiling tool used to gather diagnostics and profiling data from a
running Java application.
Its performance overhead is negligible and that’s usually below 1%. Hence it
can be used in production applications.
Before Java 11, both Java Flight Recorder (JFR) and Java Mission
Control (JMC) are commercial products and only available in Oracle
JDK, and we can enable the JFR features via the following
commands:
$ java -XX:+UnlockCommercialFeatures -XX:+FlightRecorder
MyHelloWorldApp

10.HTTP Client API

HTTP Client
—————————
Http CLient API.
The new API supports both HTTP/1.1 and HTTP/2. It is designed to improve
the overall performance of sending requests by a client and receiving
responses from the server. It also natively supports WebSockets.
Example 1.

package jdk11;

import java.io.IOException;

import java.net.URI;

import java.net.http.HttpClient;

import java.net.http.HttpRequest;

import java.net.http.HttpResponse;
public class httpClient {

public static void main(String[] args) throws IOException, InterruptedException {

var url="https://www.google.com"; // any url can take

var request=HttpRequest.newBuilder().GET().uri(URI.create(url)).build();

var client=HttpClient.newBuilder().build();

var response=client.send(request, HttpResponse.BodyHandlers.ofString());

System.out.println(response.statusCode());

System.out.println(response.body());

}}

Example 2.

package jdk11;

import java.io.IOException;

import java.net.Authenticator;

import java.net.InetSocketAddress;

import java.net.ProxySelector;

import java.net.URI;

import java.net.http.HttpClient;

import java.net.http.HttpRequest;

import java.net.http.HttpResponse;

import java.time.Duration;

public class httpClientOracle {

public static void main(String[] args) throws Exception {

var url="https://www.google.com";
var client=HttpClient.newBuilder()

//.authenticator(Authenticator.getDefault())

.connectTimeout(Duration.ofSeconds(200))

//.cookieHandler(null)

//.executor(null)

.followRedirects(HttpClient.Redirect.NORMAL)

// .proxy(ProxySelector.of(new InetSocketAddress("https://www.google.com",8080)))

//.sslContext(null)

//.sslParameters(null)

.version(HttpClient.Version.HTTP_2) //http_1, http_2

.build();

var request=HttpRequest.newBuilder()

.uri(URI.create(url))

.GET()

.version(HttpClient.Version.HTTP_2)

.build();

var response=client.send(request, HttpResponse.BodyHandlers.ofString());

System.out.println(response.statusCode());

//System.out.println(response.body());

Example 3-> for reading json data from particular url path, we also can
perform CRUD operation by using of PUT,POST,PATCH,DELETE Method at
place of GET method.

Step-1.

package jdk11;

public class Post {


private int id;
private int userId;
private String title;
private String body;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
@Override
public String toString() {
return "Post [id=" + id + ", userId=" + userId + ", title=" + title + ", body=" + body + "]";
}}

Step 2:-
package jdk11;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;

public class HttpClientGetReq {

public static void main(String[] args)throws Exception {


var url="https://www.jsonDataPlaceHolder.com"; // url has no json data so throwing
exception
// httprequest
var client=HttpClient.newHttpClient();
var request=HttpRequest.newBuilder()
.GET()
.uri(URI.create(url))
.build();

HttpResponse<String> response=client.send(request,
HttpResponse.BodyHandlers.ofString());

// parse JSON into Objects


ObjectMapper mapper=new ObjectMapper();

List<Post> posts=mapper.readValue(response.body(),new TypeReference<List<Post>>()


{});

posts.forEach(System.out::println);

System.out.println(response.statusCode());
}

}
output:- url has no json data so throwing exception

11. Reading/Writing String to and from the Files.

Java 11 strives to make reading and writing of String


convenient.

It has introduced the following methods for reading and writing


to/from the files:
 readString()
 writeString()
Following code showcases an example of this
Path path = Files.writeString(Files.createTempFile("test", ".txt"),
"This was posted on JD");
System.out.println(path);
String s = Files.readString(path);
System.out.println(s); //This was posted on JD

12.ChaCha20 and Poly 1305 Cryptographic Algorithms

ChaCha20 encryption uses the key and IV (initialisation value, nonce) to


encrypt the plaintext into a cipher-text of equal length.
Poly1305 generates a MAC (Message Authentication Code) and appending
it to the cipher-text. In the end, the length of the cipher-text and
plaintext is different.

How it works?
The inputs to ChaCha20 encryption and decryption:
 A 256-bit secret key (32 bytes)
 A 96-bit nonce (12 bytes)
 A 32-bit initial count (4 bytes)
ChaCha20 Encryption.
(plain text) + (secrect key | nonce | initial count) -> `ChaCha20` -> ciphertext
(encrypted text).
ChaCha20 Decryption.
ciphertext + (secrect key | nonce | initial count) -> `ChaCha20` -> plain text.
The ChaCha20 encryption uses the key and IV (initialization value, nonce +
initial count) to encrypt the plaintext into a ciphertext of equal length.
The nonce and secret key must be unique for each encryption. The nonce
and initial count are ok to be publicly known, but the secret key must be
private and keep it confidential.
ChaCha20 Java Implementation
Download the JDK source code and find this class ChaCha20Cipher for
ChaCha20 algorithm implementation.
ChaCha20Cipher.java
package com.sun.crypto.provider;

/**
* Implementation of the ChaCha20 cipher, as described in RFC 7539.
*
* @since 11
*/
abstract class ChaCha20Cipher extends CipherSpi {
//...
}
13.Improve Aarch64 Intrinsics.

Improve the existing string and array intrinsics, and implement new intrinsics
for the java.lang.Math sin, cos, and log functions, on AArch64 processors.

 Compare to and match the performance of other architectures


 Tune generic AArch64 port intrinsics for optimal performance on
a single ARM64 architecture implementation only
 Port intrinsics to the ARM CPU port

Specialised CPU architecture-specific code patterns improve the


performance of user applications and benchmarks.

14. ZGC: A Scalable Low-Latency Garbage Collector.

Java 11 has introduced a low latency GC. This is an experimental feature.


It’s good to see that Oracle is giving importance to GC’s.

Goals
 GC pause times should not exceed 10ms
 Handle heaps ranging from relatively small (a few hundreds of
megabytes) to very large (many terabytes) in size
 No more than 15% application throughput reduction compared
to using G1
 Lay a foundation for future GC features and optimisations
leveraging coloured pointers and load barriers
 Initially supported platform: Linux/x64
We have strong ambitions to meet these goals for a large set of
relevant workloads. At the same time, we want to acknowledge that
we don't see these goals as hard requirements for every
conceivable workload.

15. Deprecate the Nashorn JavaScript Engine

Nashorn JavaScript script engine and APIs are deprecated thereby indicating
that they will be removed in the subsequent releases.
This removal does not affect, in any way, the javax.script API.

You might also like