Type something to search...
Java Features
Photo by Nolan Issac @ Unsplash

Java Features

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:

FeatureLink
1Compact Source Files and Instance Main MethodsJEP-512
2Flexible Constructor BodiesJEP-513
3Scoped ValuesJEP-506
4Module Import DeclarationsJEP-511
5Compact Object HeadersJEP-519
6Primitive Types in Patterns, instanceof, and switch - Third PreviewJEP-507
7Vector API - Tenth IncubatorJEP-508
8Structured Concurrency - Fifth PreviewJEP-505
9Stable Values (Preview)JEP-502

Java 24

GA Date: Mar 18, 2025.

Major Java 24 new features were:

FeatureLink
1Stream GatherersJEP-485
2Class-File APIJEP-484
3Ahead-of-Time Class Loading & LinkingJEP-483
4Synchronize Virtual Threads without PinningJEP-491
5Primitive Types in Patterns, instanceof, and switch - Second PreviewJEP-488
6Scoped Values - Third PreviewJEP-487
7Vector API - Ninth IncubatorJEP-489
8Structured Concurrency - Fourth PreviewJEP-499
9Module Import Declarations - Second PreviewJEP-494
10Flexible Constructor Bodies - Third PreviewJEP-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 method java.lang.Process#waitFor(Duration) uses java.time.Duration so that the user will not be confused with the unit because existing waitFor() 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:

FeatureLink
1Markdown Documentation CommentsJEP-467
2Primitive Types in Patterns, instanceof, and switch - PreviewJEP-455
3Scoped Values - Third PreviewJEP-481
4Vector API - Eighth IncubatorJEP-469
5Structured Concurrency - Third PreviewJEP-480
6Class-File API - Second PreviewJEP-466
7Stream Gatherers - Second PreviewJEP-473
8Module Import Declarations - PreviewJEP-476
9Implicitly Declared Classes and Instance Main Methods - Third PreviewJEP-477
10Flexible Constructor Bodies - Second PreviewJEP-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:

FeatureLink
1Unnamed Patterns and VariablesJEP-456
2Foreign Function & Memory APIJEP-454
3Launch Multi-File Source-Code ProgramsJEP-458
4String Templates - Second PreviewJEP-459
5Scoped Values - Second PreviewJEP-464
6Vector API - Seventh IncubatorJEP-460
7Structured Concurrency - Second PreviewJEP-461
8Statements before super(…) (Preview)JEP-447
9Class-File API - PreviewJEP-457
10Stream Gatherers - PreviewJEP-461

22.1 Additional

  • Support Unicode 15.1

  • New Constants for 32-bit UTF Charsets: Three new constants UTF_32, UTF_32BE and UTF_32LE in java.nio.charset.StandardCharsets class 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, Baz is typically formatted as Foo, Bar, and Baz in US English, while in French it is Foo, 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, OR for “or” concatenation, and UNIT for concatenation suitable for units for the locale.

  • New equiDoubles() Method to java.util.random.RandomGenerator: A new method equiDoubles() has been added to java.util.random.RandomGenerator. equiDoubles() guarantees a uniform distribution, provided the underlying nextLong(long) method returns uniformly distributed values, that is as dense as possible. It returns a DoubleStream rather 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() and nextDouble() 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:

FeatureLink
1Record PatternsJEP-440
2Pattern Matching for switchJEP-441
3Virtual ThreadsJEP-444
4Sequenced CollectionsJEP-431
5String Templates - PreviewJEP-430
6Unnamed Patterns and Variables - PreviewJEP-443
7Unnamed Classes and Instance Main Methods - PreviewJEP-445
8Scoped Values - PreviewJEP-446
9Vector API - Sixth IncubatorJEP-448
10Foreign Function & Memory API - Third PreviewJEP-434
11Structured Concurrency - PreviewJEP-437

21.1 Additional

  • Unicode Emoji Properties: The following six new methods are added to java.lang.Character for 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.Pattern class. 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() and StrictMath.clamp() Methods: The methods Math.clamp() and StrictMath.clamp() are added to conveniently clamp the numeric value between the specified minimum and maximum values. Four overloads are provided in both Math and StrictMath classes for int, long, float, and double types. 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) and indexOf(String,int,int) methods to support a range of indices (JDK-8302590): Two new methods indexOf(int ch, int beginIndex, int endIndex) and indexOf(String str, int beginIndex, int endIndex) are added to java.lang.String to support forward searches of character ch, and of String str, 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 to String and java.util.regex.Pattern: Unlike the split() methods, these new splitWithDelimiters() methods in java.lang.String and java.util.regex.Pattern return an alternation of strings and matching delimiters, rather than just the strings.

  • The java.net.http.HttpClient is now AutoCloseable

  • New StringBuilder and StringBuffer repeat methods: The methods public StringBuilder repeat(int codePoint, int count) and public StringBuilder repeat(CharSequence cs, int count) have been added to java.lang.StringBuilder and java.lang.StringBuffer to simplify the appending of multiple copies of characters or strings. For example, sb.repeat('-', 80) will insert 80 hyphens into the value of the java.lang.StringBuilder sb object.

Java 20

GA Date: Mar 21, 2023.

Major Java 20 new features were:

FeatureLink
1Scoped Values - IncubatorJEP-429
2Record Patterns - Second PreviewJEP-432
3Pattern Matching for switch - Fourth PreviewJEP-433
4Foreign Function & Memory API - Second PreviewJEP-434
5Virtual Threads - Second PreviewJEP-436
6Structured Concurrency - Second IncubatorJEP-437
7Vector API - Fifth IncubatorJEP-438

20.1 Additional

  • Support Unicode 15.0

Java 19

GA Date: Sep 20, 2022.

Major Java 19 new features were:

FeatureLink
1Record Patterns- PreviewJEP-405
2Foreign Function & Memory API - PreviewJEP-424
3Virtual Threads - PreviewJEP-425
4Vector API - Fourth IncubatorJEP-426
5Pattern Matching for switch - Third PreviewJEP-427

19.1 Additional

  • Support Unicode 14.0

  • Additional date/time formats are now introduced in java.time.format.DateTimeFormatter/DateTimeFormatterBuilder classes. In prior releases, only 4 predefined styles, i.e., FormatStyle.FULL/LONG/MEDIUM/SHORT are available. Now the users can specify their own flexible style with this new DateTimeFormatter.ofLocalizedPattern(String requestedTemplate) method. For example, DateTimeFormatter.ofLocalizedPattern("yMMM") produces a formatter, which can format a date in a localized manner, such as Feb 2022 in the US locale, while 2022年2月 in the Japanese locale. Supporting method DateTimeFormatterBuilder.appendLocalized(String requestedTemplate) is also available.

  • New static factory methods have been introduced to allow creation of HashMap and related instances that are preallocated to accommodate an expected number of mappings or elements. After using the HashMap.newHashMap method, the requested number of mappings can be added to the newly created HashMap without it being resized. There are similar new static factory methods for LinkedHashMap, WeakHashMap, HashSet, and LinkedHashSet. The complete set of new methods is:

    • HashMap.newHashMap
    • LinkedHashMap.newLinkedHashMap
    • WeakHashMap.newWeakHashMap
    • HashSet.newHashSet
    • LinkedHashSet.newLinkedHashSet

    The int argument 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 the int argument constructors.

Java 18

GA Date: Mar 22, 2022.

Major Java 18 feature were:

FeatureLink
1UTF8 by defaultJEP-400
2Simple web serverJEP-408
3Code snippets in Java API documentationJEP-413
4Reimplement core-reflection with method handlesJEP-416
5Vector API - third incubatorJEP-417
6Internet-Address resolutionJEP-418
7Foreign function and memory APIs - second incubatorJEP-419
8Pattern Matching for switch - second previewJEP-420
9Deprecated finalization for removalJEP-421

Java 17 (LTS)

GA Date: Sep 14, 2021.

Major Java 17 new features were:

FeatureLink
1Sealed classes and interfacesJEP-409
2Pattern Matching for switch - PreviewJEP-406
3Foreign Function & Memory API - incubatorJEP-412
4Vector API - second incubatorJEP-417

All other JEPs and related documents available at JDK 17 Project

17.1 Additional

  • A new interface java.time.InstantSource has been introduced. This interface is an abstraction from java.time.Clock that 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:

FeatureLink
1Pattern matching for instanceofJEP-394
2RecordsJEP-395
3Enable C++14 language featuresJEP-347
4Packaging toolJEP-392
5Migrate from mercurial to gitJEP-357
6Migrate to githubJEP-369
7ZGC: concurrent thread-stack processingJEP-376
8Unix-Domain socket channelsJEP-380
9Alpine Linux portJEP-386
10Elastic MetaspaceJEP-387
11Windows/AArch64 portJEP-388
12Strongly encapsulate jdk internals by defaultJEP-396
13Vector API (Incubator)JEP-338
14Foreign linker api - incubatorJEP-389
15Foreign-Memory access API - third incubatorJEP-393
16Sealed classes - second previewJEP-397

16.1 Additional

  • JEP-390: Warnings for Value-Based Classes (Project Valhalla)
  • A new method toList has been added to the java.util.Stream interface.

Java 15

GAed on Sep 15, 2020.

Noted changes of Java 15 are:

FeatureLink
1Text BlocksJEP-378
2Removed the Nashorn JavaScript engineJEP-372
3Sealed classes - previewJEP-360
4Record classes - second previewJEP-384
5Pattern matching for instanceof - second previewJEP-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 isEmpty default Method to CharSequence
  • 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.

Records feedback

 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:

  1. Fields of a record are implicitly final. This means you cannot reassign them. However, objects which are assigned can be mutable.
  2. Restriction: They are declared as final classes, so we can’t inherit from them. java.lang.Record is a super class that can’t be extended.
  3. 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.
  4. Restriction: You can add static members to it, but can’t create instance method.
  5. Records can implement interfaces.
  6. For each component, there is an accessor method, e.g. max and min.

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 instanceof in 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 in Locale.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 work
    • ArrayList<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-344: Abortable mixed collection
    • JEP-346: Return unused committed memory to OS
  • JEP-334: JVM constant API (Project Valhalla)
  • JEP-341: default CDS archive
  • Supports for Unicode 11
  • Support for Compact Number Formatting - NumberFormat supports 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

  1. JEP-307: Parallel Full GC for G1
  2. JEP-310: Application Class-Data sharing
  3. JEP-217: Experimental Java-based JIT compiler (Graal, not the GraalVM)
  4. JEP-316: Heap allocation on alternative devices (Intel)

10.3 73 New APIs

Few of them:

  1. List, Set, Map.copyOf(Collection) // static method returns unmodifiable collection
  2. Collectors
    • toUnmodifiableList()
    • toUnmodifiableMap()
    • toUnmodifiableSet()
  3. 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

Related Posts

Handling of blob in JPA and JDBC

Handling of blob in JPA and JDBC

You can store large JSON/String objects in RDBMS with blob. Oracle recommends blob for storing JSON objects. In this article, we'll learn it how to handle it using JPA.

read more
Java Finalizer and Cleaner

Java Finalizer and Cleaner

Why finalization? why it got deprecated? and its alternatives Cleaner & try-with-resource.

read more
Java Recipes - Part 1

Java Recipes - Part 1

You can store large JSON/String objects in RDBMS with blob. Oracle recommends blob for storing JSON objects. In this article, we'll learn it how to handle it using JPA.

read more