[JAVA] JDK12 that makes you feel like you understand in 3 minutes

Java Advent Calendar 2018 This is the article on the 14th day. JDK12 will be released next year, so here are some of the 12 changes.

Features JEP (JDK Enhancement Proposal) included in JDK12 is as follows As of 12/6/2018

89: Shenandoah: A Low-Pause-Time Garbage Collector   (Experimental) 230: Microbenchmark Suite 325: Switch Expressions (Preview) ** 326: Raw String Literals (Preview) ** ← May be dropped from JDK12 (updated 12/14/2018) 334: JVM Constants API 340: One AArch64 Port, Not Two 341: Default CDS Archives 344: Abortable Mixed Collections for G1 346: Promptly Return Unused Committed Memory from G1

https://openjdk.java.net/projects/jdk/12/

In this article, two changes to Java syntax have impacted many Java programmers.

I will explain about.

JEP325: Switch Expressions (Preview) It is a specification of Project Amber. A slightly improved representation of Java's switch syntax.

Until now, the switch syntax was not intuitive because it depended on the order in which break statements appeared, and that became the source of potential bugs.

//Switch statements so far
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 following is an improved switch statement

//Improved switch statement
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);
}

--You can write multiple case labels ---> can be written like a lambda expression --No break statement required

Pretty refreshing: relaxed:

Assignment case to variable

A common case in switch statements is assignment to a variable.

//Switch statements so far
int numLetters;
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        numLetters = 6;
        break;
    case TUESDAY:
        numLetters = 7;
        break;
    case THURSDAY:
    case SATURDAY:
        numLetters = 8;
        break;
    case WEDNESDAY:
        numLetters = 9;
        break;
    default:
        throw new IllegalStateException("Wat: " + day);
}

The assignment process is written in each case, but this can be written as follows.

//Improved switch statement
int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY                -> 7;
    case THURSDAY, SATURDAY     -> 8;
    case WEDNESDAY              -> 9;
};

Also, you can write like this.

int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY: break 6;
    case TUESDAY:                break 7;
    case THURSDAY, SATURDAY:     break 8;
    case WEDNESDAY:              break 9;
};

Error pattern

Some things to watch out for

Case 1

final int num = 3;
String str = switch(num) {
    case 1 -> "one";
    case 2 -> "two";
};

This way of writing will result in a compilation error. The error message is "the switch expression does not cover all possible input values" In other words, cover all possible values of the switch argument as a conditional branch of the switch! That is.

In this case, write all possible values of int in case to solve: rolling_eyes: (stupid If you write default instead, the build will succeed.

final int num = 3;
String str = switch(num) {
    case 1 -> "one";
    case 2 -> "two";
    default -> "non";
};

Case 2

final int num = 3;
String str = switch(num) {
    case 1: break "one";
    case 2 -> "two";
    default -> "non";
};

This also results in a compilation error. The error message is "different case kinds used in the switch" Unify the writing style! That.

326: Raw String Literals (Preview) The expression of string literals becomes simple. When writing URL paths, regular expressions, and multi-line character strings in the source code, escaping and inserting line breaks has reduced productivity and readability, but you are freed from such annoyance.

Enclose the string in "` (backticks) "instead of" "(double quotes)".

File path example

Runtime.getRuntime().exec("\"C:\\Program Files\\foo\" bar");
Runtime.getRuntime().exec(`"C:\Program Files\foo" bar`);

Regular expression example

System.out.println("this".matches("\\w\\w\\w\\w"));
System.out.println("this".matches(`\w\w\w\w`));

Multi-line example

String html = "<html>\n" +
              "    <body>\n" +
              "		    <p>Hello World.</p>\n" +
              "    </body>\n" +
              "</html>\n";
String html = `<html>
                    <body>
                       <p>Hello World.</p>
                   </body>
               </html>
              `;

Finally

Both are Preview status, so there may be changes in the future, and I think that JDK13 or later can be used in actual production (business). So please enjoy it as much as you can touch and play with JDK12. Also, if you do not add the "--enable-preview" option when compiling and executing, an error will occur.

Recommended Posts

JDK12 that makes you feel like you understand in 3 minutes
A simple analogy of Java classes, instances, and objects. .. .. [Series that makes you feel like you understand]
[For beginners] You will definitely understand in 10 minutes! What is JavaBeans?
Understand in 5 minutes !! How to use Docker
[Java] Understand in 10 minutes! Associative array and HashMap