Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 11, 2020 01:00 pm GMT

How Java Has Advanced In The Past 6 Years (From Java 8 to Java 15)

Java Release Cycle

Java Release
Until version 8 , Java version release was one every 3 years ,so there were few versions with many features.

It was therefore complicated to deliver a new version of Java and complicated for developers to upgrade their applications due to the number of changes included.

This pace no longer keeps up with the reality of the IT world where everything is going faster and faster! So Java architects decided to publish a version every 6 months (therefore a fixed schedule)

In each version, all the ready features are incorporated, those that are not ready will be delivered in the next one (no more late version).

Java 8 most important Features with Examples

java 8

1) New Features in Java language
forEach() method
Java 8 has introduced forEach method in java.lang.Iterable interface so that while writing code we focus on business logic only.

foreach

Lambda Expression
The biggest new feature of Java 8 is language level support for lambda expressions (Project Lambda).
Lambda Expressions syntax is (argument) -> (body).

lambada exemples

Interfaces default and Static Methods
Prior to java 8, interface in java can only have abstract methods. All the methods of interfaces are public & abstract by default. Java 8 allows the interfaces to have default and static methods.

-Default methods : The reason we have default methods in interfaces is to allow the developers to add new methods to the interfaces without affecting the classes that implements these interfaces.

default interface method

-Static methods : in interfaces are similar to the default methods except that we cannot override these methods in the classes that implements these interfaces.
For example, there are many static methods on the new Stream interface. This makes helper methods easier to find since they can be located directly on the interface, instead of a different
class such as StreamUtil or Streams.

static interface method

Functional Interface
In Java 8 a functional interface is defined as an interface with exactly one abstract method. This even applies to interfaces that were created with previous versions of Java.
Java 8 comes with several new functional interfaces in the package, java.util.function.
-Function - takes an object of type T and returns R.
-Supplier - just returns an object of type T.
-Predicate - returns a boolean value based on input of type T.
-Consumer - performs an action with given object of type T.

lambada exemples

Method References
Method references are a special type of lambda expressions. They're often used to create simple lambda expressions by referencing existing methods.
There are four kinds of method references:
-Static methods
-Instance methods of particular objects
-Instance methods of an arbitrary object of a particular type
-Constructor
Exemple :

Reference methods

2) New Features in Java libraries
Stream API
The Stream interface is such a fundamental part of Java 8 .

We can use Java Stream API to implement internal iteration, that is better because java framework is in control of the iteration.

The Stream interface supports the map/filter/reduce pattern and executes lazily, forming the basis
(along with lambdas) for functional-style programming in Java 8.

There are also corresponding primitive streams (IntStream, DoubleStream, and LongStream) for performance reasons.

With Java 8, Collection interface has two methods to generate a Stream :
-stream():Returns a sequential stream considering collection as its source.

stream

-parallelStream() : Returns a parallel Stream considering collection as its source.

parallelStream

Optional
Java 8 comes with the Optional class in the java.util package for avoiding null return values (and thus NullPointerException).

If a value is present, isPresent() will return true and get() will return the value. Stream terminal operations return Optional object.
Some of these methods are:
-Optional reduce(BinaryOperator accumulator)
-Optional min(Comparator<? super T> comparator)
-Optional max(Comparator<? super T> comparator)
-Optional findFirst()
-Optional findAny()

Date/Time API
With Java 8, a new Date-Time API is introduced to cover the following drawbacks of old date-time API:
-Not thread safe
-Poor design
-Difficult time zone handling

Java 8 Date Time API consists of following packages:
1.java.time Package: This is the base package of new Java Date Time API. such as LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration etc. All of these classes are immutable and thread safe.

  1. java.time.chrono Package: This package defines generic APIs for non ISO calendar systems. We can extend AbstractChronology class to create our own calendar system.
  2. java.time.temporal Package: This package contains temporal objects and we can use it for find out specific date or time related to date/time object. For example, we can use these to find out the first or last day of the month. You can identify these methods easily because they always have format withXXX.
  3. java.time.zone Package: This package contains classes for supporting different time zones and their rules.

Java 9 most important Features with Examples

java9

Java 9 included better support for multi-gigabyte heaps, better native code integration, a different default garbage collector (G1, for "shorter response times") and a self-tuning JVM.

Java Platform Module System (Project Jigsaw)
It is a new kind of Java programing component that can be used to collect Java code (classes and packages). The main goal of this project is to easily scale down application to small devices. In Java 9, JDK itself has divided into set of modules to make it more lightweight. It also allows us to develop modular applications.

JShell: the interactive Java REPL
JShell is a REPL (Read Evaluate Print Loop) tool and run from the command line.
It is an interactive Java Shell tool, it allows us to execute Java code from the shell and shows output immediately.

Jshell

Process API Improvements
Java has improved its process API in Java 9 version, they have added couple new classes and methods to ease the controlling and managing.
Two new interfcase in Process API:

  • java.lang.ProcessHandle
  • java.lang.ProcessHandle.Info

process

Interface Private Methods
In Java 9, we can create private methods inside an interface. Interface allows us to declare private methods that help to share common code between non-abstract methods.

private methods

Java Collection Factory Methods
Factory methods are special type of static methods that are used to create unmodifiable instances of collections. It means we can use these methods to create list, set and map of small number of elements.
It is unmodifiable, so adding new element will throw java.lang.UnsupportedOperationException

private methods

Stream API Improvement
The Streams API is arguably one of the best improvements to the Java standard library in a long time.
In Java 9, Stream API has improved and new 4 methods are added to the Stream interface :iterate(), dropWhile(), takeWhile(), ofNullable().

stram improvement

Reactive Streams
Java SE 9 Reactive Streams API is a Publish/Subscribe Framework to implement Asynchronous, Scalable and Parallel applications.
Reactive Streams is about asynchronous processing of stream, so there should be a Publisher and a Subscriber. The Publisher publishes the stream of data and the Subscriber consumes the data.

reactive stream

HTTP 2 Client
A new way of performing HTTP calls arrives with Java 9. This much overdue replacement for the old HttpURLConnection API also supports WebSockets and HTTP/2 protocol.
It supports both Synchronous (Blocking Mode) and Asynchronous Modes.

HTTP2

G1 Garbage Collector
The Garbage-first garbage collector, aka G1, is a concurrent multi-threaded GC. It mostly works alongside the application threads (much like the concurrent mark sweep GC) and is designed to offer shorter, more predictable pause times while still achieving high throughput.

Other new Fectures
-Stack-Walking API
-Filter Incoming Serialization Data
-Deprecate the Applet API
-Indify String Concatenation
-Enhanced Method Handles
-Java Platform Logging API and Service
-Compact Strings
-Parser API for Nashorn
-Javadoc Search
-HTML5 Javadoc

Java 10 most important Features with Examples

java10

Java 10 is the fastest release of a java version in its 23-year history. Java has been criticized for its slow growth and evolution, but Java 10 just shattered that concept.

Local-Variable Type Inference
Local variable type inference is the biggest new feature in Java 10 for developers.
Similar to Javascript, Kotlin, and Scala, now Java will also have a var keyword that allows you to declare a local variable without specifying its type.

var

Time-Based Release Versioning
From JDK 10 release, Java has adopted a new schedule of a new release every six months. There is a lot of debate whether this is a practical approach or not, larger companies also appreciated the stability and the low rate of change of Java so far.

Oracle has responded to these concerns and continues to
offer long-term releases on a regular basis, but also at
longer intervals. And after Java 8, it is Java 11, which will
receive a long term support again.

In fact, Java 9 and Java 10 support has just ended, since
Java 11 is out.

Application Class-Data Sharing
This feature extends the existing CDS feature for allowing application classesto be placed in the shared archive in order to improve startup and footprint.

The general idea was that when the JVM first launched, anything loaded was serialized and stored in a file on disk that could be reloaded on future launches of the JVM.

This meant that multiple instances of the JVM shared the class metadata so it wouldnt have to load them all every time.

Parallel Full GC for G1
G1 garbage collector was made default in JDK 9.However, the full GC for G1 used a single threaded mark sweepcompact algorithm.

This has been changed to the parallel mark-sweep-compact algorithm
in Java 10 effectively reducing the stop-the-world time during full GC.

This change wont help the best-case performance times of the
garbage collector, but it does significantly reduce the worst-case
latencies.

Garbage-Collector Interface
This is one more interesting and useful Java 10 feature which improves the code isolation of different garbage collectors by introducing a common Garbage Collector Interface.

It will help in the future for adding new GC without changing existing codebase, also help in removing or housekeeping of the previous GC.

Root Certificates
With Java 10, Oracle has open-sourced the root certificates in
Oracles Java SE Root CA program in order to make OpenJDK
builds more attractive to developers and to reduce the
differences between those builds and Oracle JDK builds.

Thread-Local Handshakes
This is an internal JVM feature to improve performance.
This feature provides a way to execute a callback on threads without performing a global VM safepoint. Make it both possible and cheap to stop individual threads and not just all threads or none.

APIs Added
-List, Map & Set Interfaces are added with a static copyOf(Collection) method. Its returns an unmodifiable List, Map or Set containing the entries provided. For a List, if the given List is subsequently modified, the returned List will not reflect such modifications.

-Optional & its primitive variations get a method orElseThrow(). This is exactly same as get(), however the java doc states that it is a preferred alternative then get().

-Collectors class gets various methods for collecting unmodifiable collections (Set, List, Map).

java10 added API

Java 11 most important Features with Examples

java11

Java 11 is the second LTS release after Java 8. Since Java 11, Oracle JDK would no longer be free for commercial use.

Running Java File
We can avoid the compilation phase. We can compile execute in one command. We use the java command. It will implicitly compile without saving the.class file.

Java String Methods
1) isBlank(): This method returns true if the string is empty or contains only white spaces code points.

isBlank

2) lines() : returns a reference for a stream of strings that are substrings we received after splitting by lines.

lines

3) strip(), stripLeading() and the stripTrailing : remove white spaces from the beginning, the ending and the remr of the string. Itis a 'Unicode-Aware' evolution of trim();

strip

4) repeat(): method repeats the string on which it is invoked the number of times it receives.
repeat

Using var in Lambda Expressions
As of Java 11 we can use the var keyword within lambda expressions.

lambda var

When using var in a lambda expression we must use it on all parameters and we cannot mix it with using specific types.

lambda var error

Nested Based Access Control
Before Java 11, Java allows classes and interfaces to be nested within each other. These nested types have unrestricted access to each other, including to private fields, methods, and constructors.

As of Java 11, there are new methods in Class class that assist us with getting information about the created nest. These methods include the following:
getNestHost() : This returns the nest host of the nest to which this Class object belongs
getNestMembers() : This returns an array containing Class objects representing all the members of the nest to which this Class object belongs
isNestemateOf() : This determines if the given Class is a nestmate of this Class object

nested1

nested2

Epsilon: A No-Op Garbage Collector
As of Java 11, the JVM has an experimental feature that allows us to run the JVM without any actual memory reclamation.

The goal is to provide a completely passive garbage collector implementation with a bounded allocation limit and the lowest latency overhead possible.

ZGC Scalable Low Latency GC
As of Java 11, we can use the ZGC. This new GC is available as an experimental feature.
ZGC is a scalable low latency garbage collector. It performs the expensive work concurrently without stopping the execution of application threads for more than 10ms.

HTTP Client
As of Java 11, the HTTP Client API is more standardized. The new API supports both HTTP/1.1 and HTTP/2. The new API also supports HTML5 WebSockets.

Files Reading and Writing
Java 11 introduces two new methods that significantly assist with reading and writing strings from and to files : readString(), writeString()

write read file

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 thats usually below 1%. Hence it can be used in production applications.

Java 12 most important Features with Examples

java12

Java 12 was launched on March 19 2019 , which is a part of the six-month release cycle.
It is a Non-LTS version. Hence it wont have long term support.

JVM Changes
Shenandoah A Low-Pause-Time Garbage Collector: Java 12 adds Shenandoah, an experimental garbage-collection algorithm, to reduce garbage-collection pause times by performing evacuation work concurrently with running of Java threads.

-Prompt return of unused committed memory: G1 to automatically return Java heap memory to the operating system when idle. This memory is released in a reasonable period of time when there is very low application activity.

-Abortable Mixed Collections for G1: Improvements in G1 efficiency include making G1 mixed collections abortable if they might exceed the defined pause target. This is done by splitting the mixed collection set into mandatory and optional.

-Default CDS Archives: The end goal is to improve the JDK build process by generating a class data-sharing (CDS) archive. Among the goals for this feature are:
1) Improve out-of-the-box startup time.
2) Get rid of the need to run -Xshare: dump to benefit from the CDS.

Switch Expressions
There are two main changes to switch in Java with this JEP:
1) Introduction of case L -> syntax that removes the need for break statements, because only the statements next to -> is executed.
2) switch can be an expression, so it can have a value, or it can return a value.

switch 12

File.mismatch method
Java 12 added the following method to compare two files:

file mismatch

This method returns the position of the first mismatch or -1L if there is no mismatch.

mismatch 1

mismatch result

Compact Number Formatting
Java 12 extends existing number formatting APIs to provide support for locale-sensitive compact number formatting.
Now numbers like 1000 (for example) can be formatted as "1K" (short style) or "1 thousand" (long style).

number formatter

Teeing Collectors
Teeing Collector is the new collector utility introduced in the Streams API.
This collector has three arguments Two collectors and a Bi-function.
All input values are passed to each collector and the result is available in the Bi-function.

teening collectors

Java Strings New Methods

1) java.lang.String :

-indent(int n): Adjusts the indentation of each line of this string based on the value of n, and normalizes line termination characters.

-If n > 0, then n spaces (U+0020) are inserted at the beginning of each line.
-If n < 0, then up to n white space characters are removed from the beginning of each line. If a given line does not contain sufficient white space then all leading white space characters are removed. The tab character is also treated as a single character.
-If n = 0, then the line remains unchanged. However, line terminators are still normalized

sring indent

- R transform(Function<? super String,? extends R> f): This method allows the application of a function to this string.

sring transform

2) JVM Constants API :

The Constants API methods dont have much usage for normal development related tasks.

-Optional describeConstable(): Returns an Optional containing the nominal descriptor for this instance, which is the instance itself.

DescribeConstable

-String resolveConstantDesc(MethodHandles.Lookup lookup): Resolves this instance as a ConstantDesc, the result of which is the instance itself.

resolveConstantDesc

#Java 13 most important Features with Examples#
java13

Java 13 was released for production use on 17th September 2019. There are not a lot of developer-specific features in Java 13 because of the 6-month release cycle.

Switch Expressions
We initially saw switch expressions in JDK 12. Java 13's switch expressions build on the previous version by adding a new yield statement.

switch 13

Text Blocks
Text blocks for multi-line Strings such as embedded JSON, XML, HTML, etc.It allows us to create multiline strings easily. The multiline string has to be written inside a pair of triple-double quotes.

Earlier, to embed JSON in our code, we would declare it as a String literal:

json string

Now, its useful in easily creating HTML and JSON strings in our Java program :

json html 13

Also, java.lang.String now has three new methods to manipulate text blocks:
1) formatted(Object args): its similar to the String format() method. Its added to support formatting with the text blocks.

2) stripIndent(): used to remove the incidental white space characters from the beginning and end of every line in the text block. This method is used by the text blocks and it preserves the relative indentation of the content.

3) translateEscapes(): returns a string whose value is this string, with escape sequences translated as if in a string literal.

string 13

output string 13

Dynamic CDS Archive
Class data sharing (CDS) has been a prominent feature of Java HotSpot VM for a while now. It allows class metadata to be shared across different JVMs to reduce startup time and memory footprint.
Now, the creation of CDS archive and using it is much easier.

dynamic cds

ZGC: Uncommit Unused Memory
The Z Garbage Collector was introduced in Java 11 as a low-latency garbage collection mechanism.It adds a short pause time before the heap memory cleanup. But, the unused memory was not being returned to the operating system.

Starting with Java 13, the ZGC now returns uncommitted memory to the operating system by default.

FileSystems.newFileSystem() Method
Three new methods have been added to the FileSystems class to make it easier to use file system providers, which treats the contents of a file as a file system :
-newFileSystem(Path)
-newFileSystem(Path, Map)
-newFileSystem(Path, Map, ClassLoader)

DOM and SAX Factories with Namespace Support
There are new methods to instantiate DOM and SAX factories with Namespace support:
-newDefaultNSInstance()
-newNSInstance()
-newNSInstance(String factoryClassName, ClassLoader classLoader)

dom sax

Miscellaneous Changes
Java 13 has given us a few more notable changes:
-java.time new official Japanese era name added
-javax.crypto support for MS Cryptography Next Generation (CNG)
-javax.security property jdk.sasl.disabledMechanisms added to disable SASL mechanisms
-javax.xml.crypto new String constants introduced to represent Canonical XML 1.1 URIs
-javax.xml.parsers new methods added to instantiate DOM and SAX factories with namespaces support
-Unicode support upgraded to version 12.1
-Support added for Kerberos principal name canonicalization and cross-realm referrals

Java 14 most important Features with Examples

java 14

Keeping up with the six-month cycle tradition, Java 14, another non-LTS version is scheduled to release on March 17, 2020.

Switch Expressions
Switch Expressions after staying a preview feature in the last two releases Java 12 and Java 13 have finally attained permanent status in Java 14.

switch 14

Pattern Matching for instanceof
The old way to typecast a type to another type is:

instance old

The new way is :

instance new

In the above code, the instance jd would be only assigned if obj is of type Journaldev. The scope of the variable is limited to the conditional block only.

Helpful NullPointerExceptions
Improvement in NullPointerExceptions exception message generated by JVM.

Before Java 14:

NullPointer old

Java 14 introduced a new JVM feature which gives better insights with a more descriptive stack as shown below:

NullPointer new

Records
We need to write a lot of low-value, repetitive code to write a simple data carrier class responsibly: constructors, accessors, equals(), hashCode(), toString(), etc. To avoid this repetitive code, Java is planned to use record.

Before Java 14 :

records old

After Java 14 :

record new

Furthermore, we can add additional fields, methods, and constructor to the record in the following way:

record extra PNG

Few important things to note about Records:
-A record can neither extend a class nor it can be extended by another class. Its a final class.
-Records Can Implement Interfaces.
-Records support multiple constructors.
-Records Allow Modifying Accessor Methods.
-Records cannot be abstract.
-Records cannot extend any other class and cannot define instance fields inside the body. Instance fields must be defined in the state description only.
-Declared fields are private and final.
-The body of a record allows static fields and methods.

Text Blocks
Text Blocks were introduced as a preview feature in Java 13 with the goal to allow easy creation of multiline string literals. Its useful in easily creating HTML and JSON or SQL query strings.

In Java 14, Text Blocks are still in preview with some new additions:
-Backslash for displaying nice-looking multiline string blocks.
-\s is used to consider trailing spaces which are by default ignored by the compiler. It preserves all the spaces present before it.

text blocks 14

Foreign-Memory Access API
An effective Java API is to be introduced in the Java 14 JDK, which enables Java applications to safely and efficiently access foreign memory stored outside the Java heap. The foreign-memory access API introduces three main abstractions: MemorySegment, MemoryAddress and MemoryLayout.

Java 15 most important Features with Examples

java 15

Java 15 (Java SE 15) and its Java Development Kit 15 (JDK 15) open-source has been released on 15 September 2020.

Sealed Classes
Sealed classes have been there in Kotlin since a while and Java 15 finally introduces this feature for better control over inheritance.
A class can be sealed by using the sealed modifier.

sealed class

So, the above code means, only the classes defined after the keyword permits are allowed to extend the Vehicle sealed class.

Every permitted class must be set with an explicit modifier. It can either be final or sealed or non-sealed :
-A permitted subclass thats declared final cannot be extended further.
-A permitted subclass thats declared sealed can be extended further but only by classes that are permitted by the subclass.
-A permitted subclass may be declared non-sealed can be extended further by any class. The superclass cannot restrict the subclasses further down this class hierarchy.

Hidden Classes
While most developers won't find a direct benefit from them, anyone who works with dynamic bytecode or JVM languages will likely find them useful.

The goal of hidden classes is to allow the runtime creation of classes that are not discoverable.

Classes such as these typically have a short lifecycle, and thus, hidden classes are designed to be efficient with both loading and unloading.

Foreign Memory API
Foreign memory access is already an incubating feature of Java 14. In Java 15, the goal is to continue its incubation status while adding several new features:
-A new VarHandle API, to customize memory access var handles
-Support for parallel processing of a memory segment using the Spliterator interface
-Enhanced support for mapped memory segments
-Ability to manipulate and dereference addresses coming from things like native calls

Garbage Collectors
In Java 15, both ZGC and Shenandoah will be no longer be experimental. Both will be supported configurations that teams can opt to use, while the G1 collector will remain the default.

The Nashorn JavaScript engine
Of note, The Nashorn JavaScript engine, originally introduced in Java 8, is now removed. With the introduction of GraalVM and other VM technologies recently, it's clear Nashorn no longer has a place in the JDK ecosystem.

Conclusion

This article presented the evolution of Java from Java 8 to Java 15 .

Java has evolved enormously as a language and as an ecosystem since Java 8 was released over six years ago by adding many new features help to make Java a competitive option compared to other JVM-based rivals.


Original Link: https://dev.to/wejdi_gh/how-java-has-advanced-in-the-past-6-years-from-java-8-to-java-15-4gj3

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To