Java Features
- Staff Curator
- Java
- 30 Apr, 2020
- 26 May, 2025
- 29 min read
It is very difficult to remember, which feature was released in which Java version due to 6 months release cycle. This page tracks the Java versions 8 and later and features released in respective versions. It also highlights the major features with examples.
You want to know how to enable preview feature in Java, Maven, Gradle or IDEs? Scroll down
Java 25 (LTS)
GA Date: Sep 16, 2025.
Major Java 25 new features were:
| Feature | Link | |
|---|---|---|
| 1 | Compact Source Files and Instance Main Methods | JEP-512 |
| 2 | Flexible Constructor Bodies | JEP-513 |
| 3 | Scoped Values | JEP-506 |
| 4 | Module Import Declarations | JEP-511 |
| 5 | Compact Object Headers | JEP-519 |
| 6 | Primitive Types in Patterns, instanceof, and switch - Third Preview | JEP-507 |
| 7 | Vector API - Tenth Incubator | JEP-508 |
| 8 | Structured Concurrency - Fifth Preview | JEP-505 |
| 9 | Stable Values (Preview) | JEP-502 |
Java 24
GA Date: Mar 18, 2025.
Major Java 24 new features were:
| Feature | Link | |
|---|---|---|
| 1 | Stream Gatherers | JEP-485 |
| 2 | Class-File API | JEP-484 |
| 3 | Ahead-of-Time Class Loading & Linking | JEP-483 |
| 4 | Synchronize Virtual Threads without Pinning | JEP-491 |
| 5 | Primitive Types in Patterns, instanceof, and switch - Second Preview | JEP-488 |
| 6 | Scoped Values - Third Preview | JEP-487 |
| 7 | Vector API - Ninth Incubator | JEP-489 |
| 8 | Structured Concurrency - Fourth Preview | JEP-499 |
| 9 | Module Import Declarations - Second Preview | JEP-494 |
| 10 | Flexible Constructor Bodies - Third Preview | JEP-492 |
24.1 Additional
- Stream Gatherers: Enhance the Stream API to support custom intermediate operations. This will allow stream pipelines to transform data in ways that are not easily achievable with the existing built-in intermediate operations.
- Support for Unicode 16.0
- New Method
Process.waitFor(Duration): The new overloaded methodjava.lang.Process#waitFor(Duration)usesjava.time.Durationso that the user will not be confused with the unit because existingwaitFor()method with timeout needs both a primitive time-out value and its unit.
Java 23
GA Date: Sep 17, 2024.
Major Java 23 new features were:
| Feature | Link | |
|---|---|---|
| 1 | Markdown Documentation Comments | JEP-467 |
| 2 | Primitive Types in Patterns, instanceof, and switch - Preview | JEP-455 |
| 3 | Scoped Values - Third Preview | JEP-481 |
| 4 | Vector API - Eighth Incubator | JEP-469 |
| 5 | Structured Concurrency - Third Preview | JEP-480 |
| 6 | Class-File API - Second Preview | JEP-466 |
| 7 | Stream Gatherers - Second Preview | JEP-473 |
| 8 | Module Import Declarations - Preview | JEP-476 |
| 9 | Implicitly Declared Classes and Instance Main Methods - Third Preview | JEP-477 |
| 10 | Flexible Constructor Bodies - Second Preview | JEP-482 |
23.1 Additional
-
Withdrawn String Templates: String Templates were first previewed in JDK 21 (JEP-430) and re-previewed in JDK 22 (JEP-459). After feedback and extensive discussion, Java team concluded that the feature is unsuitable in its current form. There is no consensus on what a better design will be, therefore Java team has withdrawn the feature for now, and JDK 23 will not include it.
-
Console methods with explicit Locale: Users can now output the string or display the prompt text formatted with the specified Locale, which may be independent of the default locale. The following methods have been added to java.io.Console class that take a java.util.Locale argument:
- public Console format(Locale locale, String format, Object … args)
- public Console printf(Locale locale, String format, Object … args)
- public String readLine(Locale locale, String format, Object … args)
- public char[] readPassword(Locale locale, String format, Object … args)
System.console().printf(Locale.FRANCE, "%1$tY-%1$tB-%1$te %1$tA", new Date()) // will print: 2024-mai-16 jeudi
Java 22
GA Date: Mar 19, 2024.
Major Java 22 new features were:
| Feature | Link | |
|---|---|---|
| 1 | Unnamed Patterns and Variables | JEP-456 |
| 2 | Foreign Function & Memory API | JEP-454 |
| 3 | Launch Multi-File Source-Code Programs | JEP-458 |
| 4 | String Templates - Second Preview | JEP-459 |
| 5 | Scoped Values - Second Preview | JEP-464 |
| 6 | Vector API - Seventh Incubator | JEP-460 |
| 7 | Structured Concurrency - Second Preview | JEP-461 |
| 8 | Statements before super(…) (Preview) | JEP-447 |
| 9 | Class-File API - Preview | JEP-457 |
| 10 | Stream Gatherers - Preview | JEP-461 |
22.1 Additional
-
Support Unicode 15.1
-
New Constants for 32-bit UTF Charsets: Three new constants
UTF_32,UTF_32BEandUTF_32LEinjava.nio.charset.StandardCharsetsclass have been introduced. These are 32-bit based UTF charsets that are in parallel with the existing 8-bit and 16-bit equivalents. -
Locale-Dependent List Patterns: A new class
ListFormat, which processes the locale-dependent list patterns has been introduced, based on Unicode Consortium’s LDML specification. For example, a list of three Strings:Foo,Bar,Bazis typically formatted asFoo, Bar, and Bazin US English, while in French it isFoo, Bar et Baz. The following code snippet does such formatting:ListFormat.getInstance().format(List.of("Foo", "Bar", "Baz"))Besides the default concatenation type
STANDARD(= and), the class provides two additional types,ORfor “or” concatenation, andUNITfor concatenation suitable for units for the locale. -
New
equiDoubles()Method tojava.util.random.RandomGenerator: A new methodequiDoubles()has been added tojava.util.random.RandomGenerator.equiDoubles()guarantees a uniform distribution, provided the underlyingnextLong(long)method returns uniformly distributed values, that is as dense as possible. It returns aDoubleStreamrather than individual doubles because of slightly expensive initial computations. They are better absorbed as setup costs for the stream rather than being repeated for each new computed value.The aim is to overcome some numerical limitations in the families of
doubles()andnextDouble()methods. In these, an affine transform is applied to a uniformly distributed pseudo-random value in the half-open interval[0.0, 1.0)to obtain a pseudo-random value in the half-open interval[origin, bound). However, due to the nature of floating-point arithmetic, the affine transform ends up in a slightly distorted distribution, which is not necessarily uniform.
Java 21 (LTS)
GA Date: Sep 19, 2023.
Major Java 21 new features were:
| Feature | Link | |
|---|---|---|
| 1 | Record Patterns | JEP-440 |
| 2 | Pattern Matching for switch | JEP-441 |
| 3 | Virtual Threads | JEP-444 |
| 4 | Sequenced Collections | JEP-431 |
| 5 | String Templates - Preview | JEP-430 |
| 6 | Unnamed Patterns and Variables - Preview | JEP-443 |
| 7 | Unnamed Classes and Instance Main Methods - Preview | JEP-445 |
| 8 | Scoped Values - Preview | JEP-446 |
| 9 | Vector API - Sixth Incubator | JEP-448 |
| 10 | Foreign Function & Memory API - Third Preview | JEP-434 |
| 11 | Structured Concurrency - Preview | JEP-437 |
21.1 Additional
-
Unicode Emoji Properties: The following six new methods are added to
java.lang.Characterfor obtaining Emoji character properties, which are defined in the Unicode Emoji Technical Standard (UTS #51) :- isEmoji(int codePoint)
- isEmojiPresentation(int codePoint)
- isEmojiModifier(int codePoint)
- isEmojiModifierBase(int codePoint)
- isEmojiComponent(int codePoint)
- isExtendedPictographic(int codePoint)
-
Emoji related binary properties in RegEx: Emoji-related properties introduced in (JDK-8303018) can now be used as binary properties in the
java.util.regex.Patternclass. One can match characters that have Emoji-related properties with the new\p{IsXXX}constructs. For example:Pattern.compile("\\p{IsEmoji}").matcher("🉐").matches() // returns true -
Math.clamp()andStrictMath.clamp()Methods: The methodsMath.clamp()andStrictMath.clamp()are added to conveniently clamp the numeric value between the specified minimum and maximum values. Four overloads are provided in bothMathandStrictMathclasses forint,long,float, anddoubletypes. A clamp(long value, int min, int max) overload can also be used to safely narrow a long value to int.int clampedInt = Math.clamp(50, 0, 100); // Returns 50 (within range) int clampedInt2 = Math.clamp(-10, 0, 100); // Returns 0 (less than min) int clampedInt3 = Math.clamp(150, 0, 100); // Returns 100 (greater than max) double clampedDouble = Math.clamp(3.14, 1.0, 5.0); // Returns 3.14 double clampedDouble2 = Math.clamp(-2.0, 1.0, 5.0); // Returns 1.0 -
New String
indexOf(int,int,int)andindexOf(String,int,int)methods to support a range of indices (JDK-8302590): Two new methodsindexOf(int ch, int beginIndex, int endIndex)andindexOf(String str, int beginIndex, int endIndex)are added tojava.lang.Stringto support forward searches of characterch, and of Stringstr, respectively, and limited to the specified range of indices.Besides full control on the search range, they are safer to use than indexOf(int ch, int fromIndex) and indexOf(String str, int fromIndex), respectively, because they throw an exception on illegal search ranges.
-
New
splitWithDelimiters()methods added toStringandjava.util.regex.Pattern: Unlike thesplit()methods, these newsplitWithDelimiters()methods injava.lang.Stringandjava.util.regex.Patternreturn an alternation of strings and matching delimiters, rather than just the strings. -
The
java.net.http.HttpClientis nowAutoCloseable -
New
StringBuilderandStringBufferrepeatmethods: The methodspublic StringBuilder repeat(int codePoint, int count)andpublic StringBuilder repeat(CharSequence cs, int count)have been added tojava.lang.StringBuilderandjava.lang.StringBufferto simplify the appending of multiple copies of characters or strings. For example,sb.repeat('-', 80)will insert 80 hyphens into the value of thejava.lang.StringBuildersbobject.
Java 20
GA Date: Mar 21, 2023.
Major Java 20 new features were:
| Feature | Link | |
|---|---|---|
| 1 | Scoped Values - Incubator | JEP-429 |
| 2 | Record Patterns - Second Preview | JEP-432 |
| 3 | Pattern Matching for switch - Fourth Preview | JEP-433 |
| 4 | Foreign Function & Memory API - Second Preview | JEP-434 |
| 5 | Virtual Threads - Second Preview | JEP-436 |
| 6 | Structured Concurrency - Second Incubator | JEP-437 |
| 7 | Vector API - Fifth Incubator | JEP-438 |
20.1 Additional
- Support Unicode 15.0
Java 19
GA Date: Sep 20, 2022.
Major Java 19 new features were:
| Feature | Link | |
|---|---|---|
| 1 | Record Patterns- Preview | JEP-405 |
| 2 | Foreign Function & Memory API - Preview | JEP-424 |
| 3 | Virtual Threads - Preview | JEP-425 |
| 4 | Vector API - Fourth Incubator | JEP-426 |
| 5 | Pattern Matching for switch - Third Preview | JEP-427 |
19.1 Additional
-
Support Unicode 14.0
-
Additional date/time formats are now introduced in
java.time.format.DateTimeFormatter/DateTimeFormatterBuilderclasses. In prior releases, only 4 predefined styles, i.e.,FormatStyle.FULL/LONG/MEDIUM/SHORTare available. Now the users can specify their own flexible style with this newDateTimeFormatter.ofLocalizedPattern(String requestedTemplate)method. For example,DateTimeFormatter.ofLocalizedPattern("yMMM")produces a formatter, which can format a date in a localized manner, such asFeb 2022in the US locale, while2022年2月in the Japanese locale. Supporting methodDateTimeFormatterBuilder.appendLocalized(String requestedTemplate)is also available. -
New static factory methods have been introduced to allow creation of
HashMapand related instances that are preallocated to accommodate an expected number of mappings or elements. After using theHashMap.newHashMapmethod, the requested number of mappings can be added to the newly createdHashMapwithout it being resized. There are similar new static factory methods forLinkedHashMap,WeakHashMap,HashSet, andLinkedHashSet. The complete set of new methods is:HashMap.newHashMapLinkedHashMap.newLinkedHashMapWeakHashMap.newWeakHashMapHashSet.newHashSetLinkedHashSet.newLinkedHashSet
The
intargument constructors for these classes set the “capacity” (internal table size) which is not the same as the number of elements that can be accommodated. The capacity is related to the number of elements by a simple but error-prone calculation. For this reason, programs should use these new static factory methods in preference to theintargument constructors.
Java 18
GA Date: Mar 22, 2022.
Major Java 18 feature were:
| Feature | Link | |
|---|---|---|
| 1 | UTF8 by default | JEP-400 |
| 2 | Simple web server | JEP-408 |
| 3 | Code snippets in Java API documentation | JEP-413 |
| 4 | Reimplement core-reflection with method handles | JEP-416 |
| 5 | Vector API - third incubator | JEP-417 |
| 6 | Internet-Address resolution | JEP-418 |
| 7 | Foreign function and memory APIs - second incubator | JEP-419 |
| 8 | Pattern Matching for switch - second preview | JEP-420 |
| 9 | Deprecated finalization for removal | JEP-421 |
Java 17 (LTS)
GA Date: Sep 14, 2021.
Major Java 17 new features were:
| Feature | Link | |
|---|---|---|
| 1 | Sealed classes and interfaces | JEP-409 |
| 2 | Pattern Matching for switch - Preview | JEP-406 |
| 3 | Foreign Function & Memory API - incubator | JEP-412 |
| 4 | Vector API - second incubator | JEP-417 |
All other JEPs and related documents available at JDK 17 Project
17.1 Additional
- A new interface
java.time.InstantSourcehas been introduced. This interface is an abstraction fromjava.time.Clockthat only focuses on the current instant and does not refer to the time zone.
Java 16
GA Date: Mar 16, 2021.
Major Java 16 new features were:
| Feature | Link | |
|---|---|---|
| 1 | Pattern matching for instanceof | JEP-394 |
| 2 | Records | JEP-395 |
| 3 | Enable C++14 language features | JEP-347 |
| 4 | Packaging tool | JEP-392 |
| 5 | Migrate from mercurial to git | JEP-357 |
| 6 | Migrate to github | JEP-369 |
| 7 | ZGC: concurrent thread-stack processing | JEP-376 |
| 8 | Unix-Domain socket channels | JEP-380 |
| 9 | Alpine Linux port | JEP-386 |
| 10 | Elastic Metaspace | JEP-387 |
| 11 | Windows/AArch64 port | JEP-388 |
| 12 | Strongly encapsulate jdk internals by default | JEP-396 |
| 13 | Vector API (Incubator) | JEP-338 |
| 14 | Foreign linker api - incubator | JEP-389 |
| 15 | Foreign-Memory access API - third incubator | JEP-393 |
| 16 | Sealed classes - second preview | JEP-397 |
16.1 Additional
- JEP-390: Warnings for Value-Based Classes (Project Valhalla)
- A new method
toListhas been added to thejava.util.Streaminterface.
Java 15
GAed on Sep 15, 2020.
Noted changes of Java 15 are:
| Feature | Link | |
|---|---|---|
| 1 | Text Blocks | JEP-378 |
| 2 | Removed the Nashorn JavaScript engine | JEP-372 |
| 3 | Sealed classes - preview | JEP-360 |
| 4 | Record classes - second preview | JEP-384 |
| 5 | Pattern matching for instanceof - second preview | JEP-375 |
For more information refer the Java 15 changes.
15.1 Sealed Classes and Interfaces
A sealed class or interface restricts, which other classes or interfaces may extend it. Sealed classes/interfaces are useful to creating secure hierarchies by decoupling the accessibility from extensibility, that in turn gives control to API developers to expose interfaces while still controlling all the implementations.
Sealed class/interface, like enums captures alternative in domain models, allowing developers and compilers to reason about the exhaustiveness (such as in switch or in object casting). It also gel well with records and pattern matching to support data-centric form of programming.
More on Sealed classess and interfaces
Sealed are also known as sum types (similar to Scala, Haskell or Meta Language - ML). To find out the answer why it is also known as sum type, let’s create a sealed interface Shape.
sealed interface Shape permits Circle, Rectangle {}
record Circle(Point center, int radius) implements Shape { }
record Rectangle(Point lowerLeft, Point upperRight) implements Shape { }
// It can also be re-written as following if all subtypes are declared in same complilation unit
sealed interface Shape {
record Circle(Point center, int radius) implements Shape { }
record Rectangle(Point lowerLeft, Point upperRight) implements Shape { }
}
Shape either can only be Circle or Rectangle. The set of all Shapes is equal to set of all Circles plus set of all Rectangles. Therefore, sealed are also known as sum types.
Exhaustiveness It helps us in two ways using casting and pattern matching:
if (shape instanceof Circle c) {
// compiler has already cast shape to Circle for us, and bound it to c
System.out.printf("Circle of radius %d%n", c.radius());
}
// future version of switch (v16?)
float area = switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> Math.abs((r.upperRight().y() - r.lowerLeft().y())
* (r.upperRight().x() - r.lowerLeft().x()));
// no default needed because compiler knows the available subtypes from Shape declaration
}
Sums of products are generalized enums
This pattern show up everywhere: events in a UI system, return codes in a service-oriented system, messages in a protocol, etc
// associate mass and radius with each constant
enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
...
}
//A sealed class enumerates a fixed list of KINDS of instances
sealed interface Celestial {
record Planet(String name, double mass, double radius)
implements Celestial {}
record Star(String name, double mass, double temperature)
implements Celestial {}
record Comet(String name, double period, LocalDateTime lastSeen)
implements Celestial {}
}
// switch exhaustively over the various kinds of celestial bodies
// This switch will be available in future release
switch (celestial) {
case Planet(String name, double mass, double radius): ...
case Star(String name, double mass, double temp): ...
case Comet(String name, double period, LocalDateTime lastSeen): ...
}
Note:
Subtypes of a sealed class must be more explicit about their extensibility; a subtype of a sealed class must be either sealed, final, or explicitly marked non-sealed. (Records and enums are implicitly final, so do not need to be explicitly marked as such.) It is an error to mark a class or interface as non-sealed if it does not have a sealed direct supertype.
Source of sealed class is a essay written by Brian Goetz. He also provides a use case, if this feature was available at the time of writing the Future feature in Java 5. How it could have be written. A fascinating outcome.
15.2 Additional
- JEP-371: Hidden Classes (Project Valhalla)
- Added
isEmptydefault Method toCharSequence - Support for Unicode 13.0
Java 14
GAed on Mar 17, 2020
14.1 Switch expression (Standard)
Java 13 and Java 12 contains the details about it. It made the standard feature specification entry in Java 14.
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
default -> {
String s = day.toString();
int result = s.length();
yield result;
}
};
14.2 Records (Preview)
There are now record classes, which help alleviate the pain of writing a lot of boilerplate with Java.
Records focus on certain domain classes whose purpose is only to store data in fields and that do not declare any custom behaviors.
Have a look at this Java 14 class, which only contains data, (potentially) getters/setters, equals/hashcode, toString.
final class Point {
public final int x;
public final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// Getters
// state-based implementations of equals, hashCode, toString
// nothing else
}
// With records, it can now be written like this:
// With a record, you “automatically” get the implementations of equals, hashCode, and toString in addition to the constructor and getters.
record Point(int x, int y) { }
// Can have compact constructor
// Point p = new Point(10, 10);
record Point(int x, int y) {
public Point {
if (x < 0) {
throw new IllegalArgumentException("x can't be less than zero");
}
if (y < 0) {
throw new IllegalArgumentException("y can't be less than zero");
}
}
}
// can have alternative constructor: static factory
// can be used for default values
// Point p = Point.of(10);
record Point(int x, int y) {
public static Point of (int x) {
return new Point(x, 0);
}
}
// can have alternative constructor: Compound Key
record Point(int x, int y) {
public Point(Coordinate c) {
this(c.x(), c.y());
}
}
Notes:
- Fields of a record are implicitly
final. This means you cannot reassign them. However, objects which are assigned can be mutable.- Restriction: They are declared as
finalclasses, so we can’t inherit from them. java.lang.Record is a super class that can’t be extended.- Serialization: They are just transparent carriers for their fields, so there is no need to invoke the weirdness in the detail of the serialization mechanism. Instead, you can always use the public API and canonical constructor to serialize and deserialize records.
- Restriction: You can add static members to it, but can’t create instance method.
- Records can implement interfaces.
- For each component, there is an accessor method, e.g.
maxandmin.
14.3 Pattern Matching for instanceof (Preview)
The shorter syntax will remove many casts from typical Java programs. (A research paper from 2011 proposing a related language feature reported that approximately 24% of all casts follow an
instanceofin a conditional statement.)
Whereas previously you had to (cast) your objects inside an instanceof like this:
if (obj instanceof String) {
String str = (String) obj;
// use object str
}
You can now do this, effectively dropping the cast, thanks to Pattern Matching for instanceof.
if (obj instanceof String str) {
System.out.println(str.contains("hello"));
}
14.4 Packaging Tool (Incubator)
There’s an incubating jpackage tool, which allows to package your Java application into platform-specific packages, including all necessary dependencies.
- Linux: deb and rpm
- macOS: pkg and dmg
- Windows: msi and exe
14.5 Helpful NullPointerExceptions
Finally NullPointerExceptions describe exactly which variable, method invocation, field accesses, array accesses or assignment was null.
author.age = 35;
---
Exception in thread "main" java.lang.NullPointerException:
Cannot assign field "age" because "author" is null
The message now has two clear components:
- The consequence: Cannot assign field “age”
- The reason: author is null.
The enhanced diagnostics work only when you run Java with the following flag:
java -XX:+ShowCodeDetailsInExceptionMessages Java14npe
14.6 Text Blocks (Second Preview)
Java 13 introduced the Text Blocks as a preview feature. Java 14 introduces the two escape sequence \s for single space and \ to surpress the new line character insertion at the end of line. \ is helpful when you have a long line and want to split in code for easier reading.
String text = """
This is a long ...................... \
line \
""";
Additional
- Accounting Currency Format Support: Currency format instances with accounting style, in which the amount is formatted in parentheses in some locales, can be obtained by calling
NumberFormat.getCurrencyInstance(Locale)with the “u-cf-account” Unicode locale extension. For example inLocale.US, it will format to($3.27)instead of-$3.27. Refer to CLDR’s accounting currency format style for more information.
Java 13
GAed on Sep 17, 2019
13.1 JEP-355: Text Blocks (preview)
String webPage = """
<html>
<body>
<p>Hello Text Blocks!</p>
</body>
</html>
""";
System.out.println(webPage);
// output (extra line at end)
$ java WebPage
<html>
<body>
<p>Hello Text Blocks!</p>
</body>
</html>
$
13.2 JEP-354: Improved Switch Expression (Preview)
break keyword created ambiguity while returning expression value. yield is introduced to replace the break for such cases.
// improved Mix of old and new
// break is replaced by yield
int numLetters = switch(day) {
case MONDAY:
case FRIDAY:
case SUNDAY:
yield 6;
case TUESDAY:
yield 7;
case WEDNESDAY:
yield 9;
case THURSDAY:
case SATURDAY:
yield 8;
default:
throw new IllegalStateException("Huh?: " + day);
}
13.3 Project Valhalla
- Java has
- Primitives: for performance
- Objects: for encapsulation, inheritance, polymorphism OO.
- Problem is where we want to use the primitives, but we can’t
ArrayList<int>won’t workArrayList<Integer>requires boxing and unboxing, object creation, heap overhead, indirect reference
This project allows you do it - ArrayList<int>
- Project Valhalla introduces
Value Types- code like classes and work like primitives- Can have methods and fields
- Can implement interfaces
- Can use encapsulations
- Can be generic
- Can’t be mutated
- Can’t be sub-classed
You can’t change even by using reflection, which is the case with
final
13.4 Project Loom
- Making concurrent programming simpler.
- Threads are too heavy weight
- Each java thread would have the mapped OS thread. With loom each OS thread can be shared across JVM threads
- Loom will introduced fibers
- JVM level threads
- Add continuation to the JVM
- Use ForkJoinPool scheduler
- Much light weigh than thread
- less memory
- Close to zero overhead for task switch
13.5 Additional
- Unicode 12.1 support
Java 12
GAed on Mar 19, 2019
12.1 JEP-325: Switch Expression (Preview)
First preview feature in the OpenJDK (not included in Java SE).
Limitations with Switch:
- Switch construct was statement (No concept of generating a result that could be assigned)
- Rather clunky syntax
- Every case statement needs to be separated
- Must remember break (default is to fall through)
- Scope of local variable is not intuitive
// Old way
int numLetters;
switch(day) {
case MONDAY:
case FRIDAY:
case SUNDAY:
numLetters = 6;
break;
case TUESDAY:
numLetters = 7;
break;
case WEDNESDAY:
numLetters = 9;
break;
case THURSDAY:
case SATURDAY:
numLetters = 8;
break;
default:
throw new IllegalStateException("Huh?: " + day);
}
// New Way
int numLetters = switch(day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case WEDNESDAY -> 9;
case THURSDAY, SATURDAY -> 8;
default -> throw new IllegalStateException("Huh?: " + day);
};
// Mix of old and new
int numLetters = switch(day) {
case MONDAY:
case FRIDAY:
case SUNDAY:
break 6;
case TUESDAY:
break 7;
case WEDNESDAY:
break 9;
case THURSDAY:
case SATURDAY:
break 8;
default:
throw new IllegalStateException("Huh?: " + day);
}
// code blocks
int marketOpen = switch(level) {
case 1 -> {
var x = computeLevel(level)
logger.info("Computing level 1");
break x;
}
case 2 -> {
var x = computeAdvanceLevel(level)
logger.info("Computing Adv level");
break x;
}
default -> throw new IllegalStateException("level?: " + level);
}
12.2 Teeing(): Streams New Collector
- New Collector, teeing
- teeing(Collector, Collector, BiFunction)
- Collect a stream using two collectors
- Use a BiFunction to merge the two collections
Collector 1
↗ ↘
Stream -> BiFunction -> Result
↘ ↗
Collector 2
Double average = Stream.of(1, 4, 5, 2, 1, 7)
.collect(teeing(summingDouble(i -> i), counting(), (sum, n) -> sum/n));
12.3 Selected JEPs
- JEP-189: Shenandoah GC (experimental)
- G1 GC update
- JEP-334: JVM constant API (Project Valhalla)
- JEP-341: default CDS archive
- Supports for Unicode 11
- Support for Compact Number Formatting -
NumberFormatsupports formating a number in human readable format. For example, in the en_US locale, 1000 can be formatted as “1K” and 1000000 can be formatted as “1M”.
Java 11 (LTS)
GAed on Sept 25, 2018
11.1 Extended Local-Variable Syntax (JEP-323)
local variable syntax for lambdas
list.stream()
.map(s -> s.toLowerCase())
.collect(Collectors.toList());
// equals to
list.stream()
.map((var s) -> s.toLowerCase())
.collect(Collectors.toList());
// this allows to use annonations
list.stream()
.map( (@Notnull var s) -> s.toLowerCase())
.collect(Collectors.toList());
11.2 Launch Single-File Source-Code Programs (JEP-330)
-
Java 10 has three modes for the Java Launcher
- Launch a class file
- Launch the main class of a Jar
- Launch the main class of a module
-
Java 11 adds a fourth,
-
a single source of Java file
$ java Factorial.java 4 -
Single File source code Shebang
#!JAVA_HOME/bin/java --source 11 public class Factorial { public static void main(String[] args) { int n = Integer.partInt(args[0]); int r = (n == 0) ? 0 : 1; for (int i = 1; i <= n; i++) r *= i; System.out.println("n = " + n + ", n! = " + r); } } $ ./Factorial 4 n = 4, n! = 24
-
11.3 Java 11 - selected JEPs
- JEP-181: Nest-based Access Control (Project Valhalla)
- JEP-309: Dynamic Class-file constants (Project Valhalla)
- JEP-318: Epsilon garbage collector (required for performance benchmark. it does not do garbage collection)
- JEP-321: HTTP Client (Standard)
- JEP-332: Transport Layer Security (TLS) 1.3
- JEP-333: ZGC: Experimental low-latency garbage collector (avoid pauses)
- JEP-335: Nashorn - JavaScript-Engine deprecated
- JEP-328: Flight Recorder
11.4 New APIs
-
New I/O methods
- InputStream nullInputStream() // /dev/null in Linux
- OutputSteam nullOutputStream()
- Reader nullReader()
- Writer nullWriter()
-
Optional
- isEmpty() // opposite of isPresent()
-
String
- isBlank()
- Stream lines()
- String repeat(int)
- String strip() // includes Unicode spaces for removal
- String stripLeading()
- String stripTrailing()
-
Predicate interface:
not(Predicate)lines.stream().filter(s -> !s.isBlank()) // can be written as lines.stream().filter(Predicate.not(String::isBlank)) //or with static import lines.stream().filter(not(String::isBlank))
11.5 Removed Modules
- java.se.ee aggregator module has been removed.
- java.corba
- java.transaction (related with corba)
- java.activation
- java.xml.bind (jaxb)
- java.xml.ws (for SOAP apis)
- java.xml.ws.annotation
Java 10
GAed on Mar 20, 2018
10.1 var (local variable type inference, JEP 286)
Applies to only local variable (variables inside methods)
var userList = new ArrayList<String>(); // infers ArrayList<String>
var stream = list.stream(); //infers Stream<String>
for (var name: userList) { // infers String
...
}
for (var i = 0; i < 10; i++) { // infers int (not good over here )
...
}
var: Clearer try-with-resources
try (InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream, UTF_8);
BufferedReader bufferedReader =
new BufferedReader(inputStreamReader)) {
// use bufferedReader
}
// Can be changed to
try (var inputStream = socket.getInputStream();
var inputStreamReader = new InputStreamReader(inputStream, UTF_8);
var bufferedReader = new BufferedReader(inputStreamReader)) {
// use bufferedReader
}
reserved type (not keyword)
1.You can create var var = new getUserList();
2.You can’t create class public class var. However, you can create public class Var
10.2 Selected JEPs
- JEP-307: Parallel Full GC for G1
- JEP-310: Application Class-Data sharing
- JEP-217: Experimental Java-based JIT compiler (
Graal, not theGraalVM) - JEP-316: Heap allocation on alternative devices (Intel)
10.3 73 New APIs
Few of them:
- List, Set, Map.copyOf(Collection) // static method returns unmodifiable collection
- Collectors
- toUnmodifiableList()
- toUnmodifiableMap()
- toUnmodifiableSet()
- Optional.orElseThrow() // same as get()
Java 9
GAed on Sept 21, 2017.
Major features released in Java 9 were:
-
JEP-222: jshell - The Java Shell - new tool and API for interactive Java Provide an interactive tool to evaluate declarations, statements, and expressions of the Java programming language, together with an API so that other applications can leverage this functionality. Adds Read-Eval-Print Loop (REPL) functionality for Java.
The jshell tool accepts “snippets” of Java code, evaluating them and immediately displaying the results. Snippets include variable and method declarations without enclosing class. An expression snippet immediately shows its value. The jshell tool also accepts commands for displaying and controlling snippets.
The jshell tool is built on the JShell API, making the evaluation of snippets of Java code available any Java program. Refer jshell tool User’s Guide for more information.
-
Modularity (Modules) - Core Java libraries are now a set of modules
-
JEP-282: jlink: The Java linker
Java 8 (LTS)
GAed on Mar 18, 2014. Few of the prominent features of Java 8 are:
- Lambda and Method Reference
- Streams
- Optional
How to enable preview feature
Following options can be used to enable the java preview feature
Enable preview feature in command line
Use following options for java and javac commands.
java --source <version> --enable-preview <rest of the parameters>
javac --source <version> --enable-preview <rest of the parameters>
Enable preview feature in Gradle
Use following options in build.gradle file.
sourceCompatibility = <version such as JavaVersion.VERSION_15>
compileJava {
options.compilerArgs += ["--enable-preview"]
}
compileTestJava {
options.compilerArgs += ["--enable-preview"]
}
test {
jvmArgs '--enable-preview'
}
Enable preview feature in Maven
Use following options for maven-compiler-plugin and maven-surefire-plugin plugins.
...
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>15</release>
<compilerArgs>--enable-preview</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
Enable preview feature in IntelliJ IDEA
You can enable the preview feature using File → Project Structure → Project → Project SDK and Project language level menus.
Enable preview feature in Eclipse IDE
You can enable the preview feature using Preferences → Java → Compiler → Enable preview features option.
Source