Домой United States USA — software Java 9: A Look at Milling Project Coin Java 9: A Look...

Java 9: A Look at Milling Project Coin Java 9: A Look at Milling Project Coin

353
0
ПОДЕЛИТЬСЯ

JDK 9 will bring big and small tweaks to the language. Here we examine JEP 213: Milling Project Coin to learn about try-with-resources and identifier changes.
In this section, we are going to discuss the new Java 9 enhancements as part of JEP 213: Milling Project Coin. The purpose of JEP 213 is to address some rough edges. Milling Project Coin has five small amendments to the Java programming language.
In Java 8, an underscore (_) is allowed as an identifier name, but the compiler will show a warning that «It will not be supported after Java SE 8.» So Java 9 completed the removal of underscore from the set of legal identifier names.
Java 8: Warning for _ as the identifier name
Java 9: Error for _ as the identifier name
The underscore will be used as a keyword for an unnamed lambda parameter in future Java releases (JEP 302) . That’s the reason the compiler stated «_» is a keyword while compiling the Java file.
Java 7 introduced the try-with-resources statement, where resources will be closed automatically after the execution. It requires an additional variable for the resources to be assigned. But Java 9 manages the same with the final or effectively final variables. The effectively final variable is the variable or the parameter whose values will never be changed once it is initialized.
Example: int num=10;
The above num is treated as effectively final by the compiler until you change the value, so the effectively final variable is treated like the final variable unless it is changed.
Java 7: Requires the additional variable:
Java 9: Doesn’t require additional variables:
Please refer my previous post on Java 9 Interface for this section.
Java 7 introduced the @SafeVarargs annotation to final, static methods, and constructors. Java 9 extends this functionality to use for private methods, too.
Example:
Upon compiling the above code with Java 8 using the javac tool with -Xlink: unchecked to get a detailed warning, it throws two warnings, as seen below:
We can avoid this warning message by annotating the private method with the @SafeVarargs annotation in Java 9. Compile the same code by annotating the printList with @SafeVarargs.
Java 7 introduced the diamond operator () in generic class instantiation contexts. The following code shows its use:
list1 is the pre-Java 7 approach to instantiate a generic class. The actual type argument is specified while instantiating it. But list2 is instantiated without mentioning the actual type argument, which was introduced in Java 7.
The above snippet will throw the compile time error » cannot be used with anonymous classes.» But the same code will be successfully compiled in Java 9.

Continue reading...