The Future of Java - Project Amber

The Future of Java - Project Amber

Project Amber incubates smaller, productivity-oriented Java language features that have been accepted as candidate JEPs. Take a quick glimpse of the features that will arrive on the platform soon.

Project Amber incubates smaller, productivity-oriented Java language features that have been accepted as candidate JEPs. Take a quick glimpse of the features that will arrive on the platform soon.

Recently, Java changed its release cycle to a more rapidly cadence, affecting the way the language evolves overtime. With this new cadence, features can now reach the market faster. Besides that, this cadence enables the community to work on (and deliver) smaller features instead of expending all their energy on the big changes (e.g., lambda, generics, and modules).

Throughout the next sections, you will learn about Amber, the project that incubates small, productivity-oriented Java language features.

Project Amber

Project Amber, as explained on its homepage, is an effort focused on “exploring and incubating smaller, productivity-oriented Java language features that have been accepted as candidate JEPs under the OpenJDK JEP process.” At the time of writing, this project has already delivered two enhancements and is planning on delivering five more. Let’s learn about these enhancements.

Enhancements delivered

The first enhancement already released, called Local-Variable Type Inference, was introduced in Java 10 and allows developers to reduce the ceremony associated with writing Java code while maintaining Java’s commitment to static type safety. With this enhancement, developers can now declare variables like this:

var list = new ArrayList<String>(); // infers ArrayList<String>
var stream = list.stream(); // infers Stream<String>

List<String> list = new ArrayList<String>();
Stream<String> stream = list.stream();

The second enhancement, called Local-Variable Syntax for Lambda Parameters, was introduced in Java 11 and extends the Local-Variable Type Inference feature by allowing var to be used when declaring the formal parameters of implicitly typed lambda expressions. For example, with this enhancement, if you write the following code:

IntStream.of(1, 2, 3, 5, 6, 7)
          .filter((var i) -> i % 3 == 0)
          .forEach(System.out::println);

Java will have no problem identifying that the i variable is an integer.

Enhancements being developed

Besides the enhancements already released, Project Amber is planning on delivering Lambda Leftovers, Pattern Matching, Switch Expressions, Raw String Literals, and Concise Method Bodies.

Lambda Leftovers

The Lambda Leftovers enhancement aims at bringing two new features to the Java language. First, this enhancement will allow developers to use an underscore (_) to denote an unnamed lambda parameter. Second, the enhancement will allow lambda parameters to shadow variables already defined in the enclosing context. For example, this last feature will enable developers to write code as follows:

Map<String, Integer> msi = ...

String key = computeSomeKey();
msi.computeIfAbsent(key, key -> key.length());

In this case, the inner key variable will cause no conflict with the external one (derived from the computeSomeKey() call).

Pattern Matching

The Pattern Matching enhancement will allow developers to be more concise when dealing with the instanceof operator. For example, with this feature, whenever developers want to check if an object is a String and use it as such, instead of doing this:

if (obj instanceof String) {
    String s = (String) obj;
    // use s
}

They will be able to do this:

if (obj instanceof String s) {
    // can use s here
}

By using the new pattern matching feature, developers will reduce the overall number of explicit casts in Java programs considerably. For example, as type test patterns are particularly useful when writing equality methods, instead of having a method like this:

@Override public boolean equals(Object o) { 
    return (o instanceof CaseInsensitiveString) && 
        ((CaseInsensitiveString) o).s.equalsIgnoreCase(s); 
}

Developers will be able to simplify the code (and avoid the explicit cast), as shown here:

@Override public boolean equals(Object o) { 
    return (o instanceof CaseInsensitiveString cis) && 
        cis.s.equalsIgnoreCase(s); 
}

Switch Expressions

The Switch Expressions enhancement will enable developers to use the switch feature as either a statement (the traditional way) or as an expression (the simplified version). This change will simplify some code, as you can see on the following code snippets. The first one shows how you would use the traditional switch keyword to make a decision:

switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        System.out.println(6);
        break;
    case TUESDAY:
        System.out.println(7);
        break;
    case THURSDAY:
    case SATURDAY:
        System.out.println(8);
        break;
    case WEDNESDAY:
        System.out.println(9);
        break;
}

The second one shows how you would use the simplified version to achieve the same result:

switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);
}

Pretty nice, huh?

Raw String Literals

The Raw String Literals enhancement will add, as the name states, raw string literals to the Java programming language. This type of string can span multiple lines of source code and does not interpret escape sequences, such as \n, or Unicode escapes, of the form \uXXXX. Among its goals, the enhancement plans on:

  • make it easier for developers to express sequences of characters in a readable form, free of Java indicators;
  • supply strings targeted for grammars other than Java;
  • and supply strings that span several lines of source without supplying special indicators for new lines.

One good way to see the benefits of this enhancement is to consider what you would need to do to write a long SQL query:

String query = "SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB` " +
               "WHERE `CITY` = ‘INDIANAPOLIS' " +
               "ORDER BY `EMP_ID`, `LAST_NAME`;";

By using Raw String Literals you will be able to rewrite the previous code snippet as follows:

String query = ``SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`
                 WHERE `CITY` = ‘INDIANAPOLIS'
                 ORDER BY `EMP_ID`, `LAST_NAME`;
               ``;

Concise Method Bodies

The Concise Method Bodies enhancement is all about supporting more concise methods in the Java programming language. The Java 8 version, released back in 2014, introduced what is known as the Lambda Expressions enhancement. This enhancement, known as Java’s first step into functional programming, allowed developers to define methods that do not belong to any class. As such, these methods (which have a very concise syntax) can be passed around as if they were objects and can be executed on demand.

For example, prior to the Lambda Expressions introduction, if you needed to do some calculation and return an integer, you would have to find a class where to define a new method:

public static class Utils {
  public static int calculate(Object someParameter) {
    // ... calculate
    return result;
  }
}

After that, you would be able to call this method whenever you wanted, after importing the Util class. With the introduction of this new feature, you can now replace all this boilerplate with something much simpler:

ToIntFunction<Object> calculate = (Object o) -> {
  // ... calculate
    return result;
};

The code above, instead of belonging to some random class (like Utils, on the example), can be written and called right where you need it. This can be considered the first concise methods introduced in the programming language.

Now, back to the Concise Method Bodies enhancement that Project Amber will introduce, when this feature is released, developers will be able to apply this kind of syntax in more places. For example, if you ever did something like creating a method like this:

int length(String s) {
  return s.length();
}

In the near future, you will be able to rewrite it like this:

int length(String s) -> s.length();

Conclusion

As you learned in this short blog post, Project Amber is the project that you have to keep an eye on to learn about the productivity-oriented features that will arrive at the Java programming language soon.

Learn More

Introduction to Java Stream API

Learn Java from Beginner to Advanced - Complete Java Course Part 1/3

Build a Simple CRUD App with Spring Boot and Vue.js

Build a Basic App with Spring Boot and JPA using PostgreSQL

Complete Java Masterclass

Complete Step By Step Java For Testers

Java Web Service Complete Guide - SOAP + REST + Buide App

Selenium WebDriver with Java - Basics to Advanced& Interview

Java Persistence: Hibernate and JPA Fundamentals

Java Swing (GUI) Programming: From Beginner to Expert

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners

Java Essentials : Learn Core Java From Basic to Advance

Learn Java Programming Using Practical Assignments. Start Building Back-end Web Applications Robust Test Automation Frameworks By End Of The Course. Learn More!

Fundamentos de Java: Aprende Java desde cero, sin misterios | Simpliv

Fundamentos de Java: Aprende Java desde cero, sin misterios