0% found this document useful (0 votes)
232 views16 pages

Key Features of Java 11 Explained

Uploaded by

tmdjgs7zjq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
232 views16 pages

Key Features of Java 11 Explained

Uploaded by

tmdjgs7zjq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

@Pankaj Kumar

Java 11 Features
——————————
1. Importance of Java 11.
[Link] Java File with single command.
[Link] String Method.
[Link]-Variable Syntax for Lambda Parameters.
[Link] based Access Control.
[Link] class-file Constants
[Link]: A No-Op Garbage Collector
[Link] the Java EE and CORBA Modules
[Link] Recorder
[Link] Client API
11. Reading/Writing String to and from the Files.
12.ChaCha20 and Poly 1305 Cryptographic Algorithms
[Link] Aarch64 Intrinsics.
[Link]: 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 [Link]
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 [Link].*;

public class Main {


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

[Link](" ".isBlank()); //true

String s = "Anupam";
[Link]([Link]()); //false
String s1 = "";
[Link]([Link]()); //true
}
}

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


substrings split by lines.
import [Link];

public class Main {


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

String str = "JD\nJD\nJD";


[Link](str);
[Link]([Link]().collect([Link]()));
}
}
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 ";


[Link]("Start");
[Link]([Link]());
[Link]("End");

[Link]("Start");
[Link]([Link]());
[Link]("End");

[Link]("Start");
[Link]([Link]());
[Link]("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);


[Link](str); //prints ==
}
}

[Link]-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 -> [Link]()
we cannot skip them while using var:
var s1 -> [Link]()

[Link] 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() {


[Link]("hello from private method");
}

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

public static void main(String[] args){

Main m = new Main();


[Link] n = [Link] NestedMain();
[Link]();

}
}

Output:-
hello from private method

[Link] 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.

[Link]: 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.

[Link] 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 [Link] Defines the Java API for XML-Based Web
Services (JAX-WS) Services (JAX-WS), and the Web Services
Metadata API.
[Link] Tools for JAX-WS
Java Architecture for XML [Link] Defines the Java Architecture for XML Binding
Binding (JAXB) (JAXB) API.
[Link] Tools for JAXB
JavaBeans Activation Defines the JavaBeans Activation Framework
[Link]
Framework (JAF) (JAF) API.
Common Annotations [Link] 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 [Link]
APIs, and the RMI-IIOP API.
(CORBA)
Java Transaction API [Link] Defines a subset of the Java Transaction API
(JTA) (JTA) to support CORBA interoperation.
Aggregator module for the [Link] Defines the full API of the Java SE Platform.
all modules above

[Link] 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

[Link] 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 [Link];

import [Link];

import [Link];

import [Link];

import [Link];
public class httpClient {

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

var url="[Link] // any url can take

var request=[Link]().GET().uri([Link](url)).build();

var client=[Link]().build();

var response=[Link](request, [Link]());

[Link]([Link]());

[Link]([Link]());

}}

Example 2.

package jdk11;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class httpClientOracle {

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

var url="[Link]
var client=[Link]()

//.authenticator([Link]())

.connectTimeout([Link](200))

//.cookieHandler(null)

//.executor(null)

.followRedirects([Link])

// .proxy([Link](new InetSocketAddress("[Link]

//.sslContext(null)

//.sslParameters(null)

.version([Link].HTTP_2) //http_1, http_2

.build();

var request=[Link]()

.uri([Link](url))

.GET()

.version([Link].HTTP_2)

.build();

var response=[Link](request, [Link]());

[Link]([Link]());

//[Link]([Link]());

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) {
[Link] = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
[Link] = userId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
[Link] = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
[Link] = body;
}
@Override
public String toString() {
return "Post [id=" + id + ", userId=" + userId + ", title=" + title + ", body=" + body + "]";
}}

Step 2:-
package jdk11;
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link].*;

public class HttpClientGetReq {

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


var url="[Link] // url has no json data so throwing
exception
// httprequest
var client=[Link]();
var request=[Link]()
.GET()
.uri([Link](url))
.build();

HttpResponse<String> response=[Link](request,
[Link]());

// parse JSON into Objects


ObjectMapper mapper=new ObjectMapper();

List<Post> posts=[Link]([Link](),new TypeReference<List<Post>>()


{});

[Link]([Link]::println);

[Link]([Link]());
}

}
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 = [Link]([Link]("test", ".txt"),
"This was posted on JD");
[Link](path);
String s = [Link](path);
[Link](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.
[Link]
package [Link];

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

Improve the existing string and array intrinsics, and implement new intrinsics
for the [Link] 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 [Link] API.

Common questions

Powered by AI

Flight Recorder being open-sourced in Java 11 allows wider access to its capabilities for diagnostics and profiling with minimal performance overhead (below 1%). Developers benefit from better analysis tools at no additional cost, promoting consistent usage across different environments. However, its open-source nature may also lead to variations in implementation quality and support, potentially affecting reliability without proper management .

Java 11 introduces readString() and writeString() methods that simplify reading and writing strings directly to and from files, compared to earlier versions where these operations required more verbose and complex code. This improves code readability, efficiency, and ease of use for developers managing file I/O operations .

The new String methods in Java 11 like isBlank(), lines(), strip(), and repeat() provide enhanced string manipulation capabilities. isBlank() checks if a string is empty or only contains whitespace. lines() splits a string into a stream of lines. strip(), stripLeading(), and stripTrailing() remove whitespace from strings more effectively than trim(), and repeat() allows a string to be repeated a specified number of times, making common operations more concise and readable .

The ZGC garbage collector in Java 11 is designed for scalability and low latency. It maintains GC pause times under 10ms, even for large heap sizes of terabytes, which is a significant improvement over previous collectors. It uses advanced techniques like colored pointers and load barriers to achieve these goals without significantly impacting application throughput, making it suitable for applications that demand consistent low-latency performance .

Dynamic class-file constants in Java 11 allow constants to be defined at runtime through a bootstrap method, similar to dynamically linked call sites. This facility enables more flexible constant expressions and paves the way for more dynamic Java language features, potentially allowing bulk constants like arrays and integrating special rules for lazy initialization, which can lead to more efficient and adaptable application code design .

The local-variable syntax for lambda parameters in Java 11 allows developers to specify parameter types with 'var', enhancing code expressiveness by making lambda expressions more readable and concise. However, it requires all parameters to have 'var' if used, enforcing consistency but potentially increasing verbosity. This feature supports better integration with type inference mechanisms, improving the ease of working with complex method signatures .

Java 11 is important because it is the second Long-Term Support (LTS) release after Java 8, providing extended updates and support until 2026. This ensures stability and long-term usage for enterprises and developers relying on this version .

The Epsilon garbage collector is designed for performance testing environments as it eliminates memory clearance overhead, allowing for accurate performance results without interruptions from garbage collection processes. However, it is not suitable for production because it does not reclaim memory, leading to an inevitable OutOfMemoryError if the application runs for an extended period .

The HTTP Client API in Java 11 supports both HTTP/1.1 and HTTP/2, improving the performance of sending requests and receiving responses. Additionally, it natively supports WebSockets, allowing developers to utilize a broader range of web communication technologies directly in Java applications, streamlining network operations .

The removal of Java EE and CORBA modules in Java 11 reflects Oracle's focus on streamlining the core Java platform by eliminating outdated and seldom-used APIs. This decision encourages the adoption of more modern technologies and reduces Java's footprint, though it forces developers who rely on these modules to seek alternative solutions or manually add necessary libraries .

You might also like