Preview features in Java 12

Java 12 was released in March 2019 and brought several new features and improvements to the language. One of the most notable additions in Java 12 is the inclusion of preview features. Preview features are experimental features that are made available in the release but are not yet ready for production use. They allow developers to try out new language features and provide feedback to the Java development team.

Enabling preview features

To enable preview features in Java 12, you need to use the command-line option --enable-preview. This allows you to use the preview features specified in the release.

For example, if you have a Java file called Example.java that utilizes a preview feature, you can compile it by running the following command:

javac --enable-preview Example.java

Switch expressions

One of the major preview features introduced in Java 12 is switch expressions. Switch expressions provide a more concise and expressive syntax for writing switch statements. They allow you to use the -> arrow operator to return a value from a switch statement.

Here’s an example of how switch expressions can be used:

String result = switch (dayOfWeek) {
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday";
    case SATURDAY, SUNDAY -> "Weekend";
};
System.out.println(result);

This simplifies the code and eliminates the need for break statements in each case. Switch expressions are a powerful feature that can make your code more readable and maintainable.

Raw string literals

Another preview feature added in Java 12 is raw string literals. Raw string literals allow you to include line breaks and escape sequences without any special handling. They can be useful when dealing with multi-line strings or strings that contain special characters.

Here’s an example of how raw string literals can be used:

String html = `<html>
                <body>
                    <h1>Hello, Java 12!</h1>
                </body>
               </html>`;
System.out.println(html);

Raw string literals eliminate the need for escaping characters or concatenating multiple lines using the + operator. They contribute to writing more readable and maintainable code.

Conclusion

Preview features in Java 12 provide developers with the opportunity to try out new language features and provide feedback to the Java development team. Switch expressions and raw string literals are two significant preview features introduced in Java 12 that can improve code readability and maintainability.

Make sure to enable the --enable-preview option when using preview features to take full advantage of these experimental features.

[References:\

#java12 #previewfeatures