Like it and look again, develop a good habit
The updates of JAVA in the past few years are really madam... soon, JAVA 8 hasn't been used for long, 16 has been released. Since JAVA 8 released Lambda and Stream, JAVA has been like a chicken blood. With the release of a version in half a year, the donkeys of the production team have not been so diligent.
As a result, we can't keep up with the pace of JAVA release at all. Our company is still stuck in JAVA 8, and even some old systems are still using JAVA 7, which cannot be easily upgraded at all.
However, although the latest version of JAVA is not available for the time being, it is still very important to understand the main features of each new version.
This article will take you to quickly understand the main new features of JAVA 9-16, and finish your studies early and leave work early!
JAVA 9 (September 2017)
Private interface can be added to the interface
JAVA 8 adds support for the default method to the interface. This function has been upgraded again in JAVA 9. Now you can define private methods in the interface, and then call the private methods of the interface in the default method.
In this way, the code in the private method can be reused, and the code can not be disclosed
public interface TestInterface {
default void wrapMethod(){
innerMethod();
}
private void innerMethod(){
System.out.println("");
}
}
Anonymous inner classes also support the diamond operator
JAVA 5 introduced generics, and since JAVA 7 began to support the diamond operator: <>
, the type of generics can be inferred automatically:
List<Integer> numbers = new ArrayList<>();
But this diamond operator that automatically infers the type does not support anonymous inner classes, and anonymous inner classes are also supported in JAVA 9:
List<Integer> numbers = new ArrayList<>() {
...
}
Enhanced try-with-resources
try-with-resources
in JAVA 7, which can automatically close resources:
try (BufferedReader bufferReader = new BufferedReader(...)) {
return bufferReader.readLine();
}
But when you need to declare multiple resource variables, the code looks a bit disgusting. You need to write the creation process of multiple variables in try:
try (BufferedReader bufferReader0 = new BufferedReader(...);
BufferedReader bufferReader1 = new BufferedReader(...)) {
return bufferReader0.readLine();
}
This feature has been enhanced in JAVA 9, which can be automatically closed by referencing variables outside the try code block:
BufferedReader bufferReader0 = new BufferedReader(...);
BufferedReader bufferReader1 = new BufferedReader(...);
try (bufferReader0; bufferReader1) {
System.out.println(br1.readLine() + br2.readLine());
}
JAVA 10 (March 2018)
Automatic type inference of local variables (var)
JAVA 10 brings a very interesting grammar- var
, it can automatically infer the type of local variables, there is no need to write types in the future, and there is no need to rely on lombok's var
annotation to enhance
var message = "Hello, Java 10";
But this is just syntactic sugar. Variables still have types after compilation. When using it, consider maintainability issues, otherwise it will become JavaScript style if you write too much.
JAVA 11 (September 2018)
Automatic type inference in Lambda (var)
JAVA 11 also supports the var
for Lambda grammar, and additional annotations can be added through the var variable:
List<String> languages = Arrays.asList("Java", "Groovy");
String language = sampleList.stream()
.map((@Nonnull var x) -> x.toUpperCase())
.collect(Collectors.joining(", "));
assertThat(language).isEqualTo("Java, Groovy");
javac + java command a shuttle
When compiling a java file in the past, you need to compile javac into a class first, and then execute it with java. Now you can shuttle it:
$ java HelloWorld.java
Hello Java 11!
Java Flight Recorder landed on OpenJDK
Java Flight Recorder is an easy-to-use debugging and diagnostic tool, but it was previously in Oracle JDK, and it was also open sourced with JDK 11. This function can also be used in OpenJDK. It's really fragrant!
JAVA 12 (March 2019)
More concise switch syntax
In the previous JAVA version, the switch
is quite verbose. If multiple values take one logic, you need to write multiple case
:
DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
String typeOfDay = "";
switch (dayOfWeek) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
typeOfDay = "Working Day";
break;
case SATURDAY:
case SUNDAY:
typeOfDay = "Day Off";
}
With JAVA 12, this thing has become very simple, just a few lines, and! Also supports return values:
typeOfDay = switch (dayOfWeek) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Working Day";
case SATURDAY, SUNDAY -> "Day Off";
};
Instanceof + type forced conversion in one step
When dealing with the dynamic type before, when you need to instanceof
conversion, you need to judge 060aa43ce09731 first, and then force conversion to this type of processing:
Object obj = "Hello Java 12!";
if (obj instanceof String) {
String s = (String) obj;
int length = s.length();
}
Now instanceof
supports direct type conversion, and there is no need to perform an additional forced conversion:
Object obj = "Hello Java 12!";
if (obj instanceof String str) {
int length = str.length();
}
JAVA 13 (September 2019)
The switch syntax is enhanced
JAVA 12, although enhanced swtich
syntax, but not in ->
write after complex logic, JAVA 12 brings swtich
a great experience, just like lambda
like, you can write logic, and back again:
typeOfDay = switch (dayOfWeek) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> {
// do sth...
yield "Working Day";
}
case SATURDAY, SUNDAY -> "Day Off";
};
Support for Text Block
Are you still troubled by large paragraphs of string messages with line breaks, a bunch of line breaks, if you don’t break lines, it looks uncomfortable:
String json = "{\"id\":\"1697301681936888\",\"nickname\":\"空无\",\"homepage\":\"https://juejin.cn/user/1697301681936888\"}";
JAVA 13 helps you solve this disgusting problem, adds support for text blocks, and now you can happily wrap strings and spell strings, just like using templates:
String json = """
{
"id":"1697301681936888",
"nickname":"空无",
"homepage":"https://juejin.cn/user/1697301681936888"
}
""";
JAVA 14 (March 2020)
New record type, get rid of complex POJO classes
Generally, when we create a POJO class, we need to define the property list, constructor, getter/setter, which is more troublesome. JAVA 14 brings us a convenient way to create classes- record
public record UserDTO(String id,String nickname,String homepage) { };
public static void main( String[] args ){
UserDTO user = new UserDTO("1697301681936888","空无","https://juejin.cn/user/1697301681936888");
System.out.println(user.id);
System.out.println(user.nickname);
System.out.println(user.id);
}
IDEA has already supported this feature, you can directly select when creating a class:
But this is just a syntactic sugar. After compilation, it is still a Class, which is not much different from ordinary Class
More intuitive NullPointerException tips
NullPointerException is one of the most common exceptions in JAVA, but this gadget is really unfriendly. When encountering some longer chain expressions, there is no way to tell which object is null.
For example, in the following example, is innerMap
empty or effected
empty?
Map<String,Map<String,Boolean>> wrapMap = new HashMap<>();
wrapMap.put("innerMap",new HashMap<>());
boolean effected = wrapMap.get("innerMap").get("effected");
// StackTrace:
Exception in thread "main" java.lang.NullPointerException
at org.example.App.main(App.java:50)
JAVA 14 also gets to the pain points of JAVAERs, and optimizes the prompt of NullPointerException, so that you are not confused, and you can locate the "empty" at a glance!
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "java.util.Map.get(Object)" is null
at org.example.App.main(App.java:50)
Now StackTrace is very intuitive, telling you directly that the effected
is empty, no more confusion!
Safe off-heap memory read and write interface, stop playing Unsafe's sorrow operation
In the previous version, if JAVA wanted to manipulate the off-heap memory (DirectBuffer), it had to Unsafe all kinds of copy/get/offset. Now, a set of safe off-heap memory access interface has been directly added, which can easily access off-heap memory without having to engage in Unsafe operation.
// 分配 200B 堆外内存
MemorySegment memorySegment = MemorySegment.allocateNative(200);
// 用 ByteBuffer 分配,然后包装为 MemorySegment
MemorySegment memorySegment = MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(200));
// MMAP 当然也可以
MemorySegment memorySegment = MemorySegment.mapFromPath(
Path.of("/tmp/memory.txt"), 200, FileChannel.MapMode.READ_WRITE);
// 获取堆外内存地址
MemoryAddress address = MemorySegment.allocateNative(100).baseAddress();
// 组合拳,堆外分配,堆外赋值
long value = 10;
MemoryAddress memoryAddress = MemorySegment.allocateNative(8).baseAddress();
// 获取句柄
VarHandle varHandle = MemoryHandles.varHandle(long.class, ByteOrder.nativeOrder());
varHandle.set(memoryAddress, value);
// 释放就这么简单,想想 DirectByteBuffer 的释放……多奇怪
memorySegment.close();
For students who don’t know how Unsafe operates off-heap memory, you can refer to my other article " Unsafe classes used extensively for performance in the JDK, would you use it? "
The newly added jpackage packaging tool can directly package binary programs without installing JRE anymore
If you want to build an executable program before, you need to use a third-party tool to package the JRE together, or let the client computer also install a JRE to run our JAVA program.
Now JAVA has built-in jpackage
packaging tool directly to help you package binary package with one click, and finally you don’t have to worry about it.
JAVA 15 (September 2020)
ZGC and Shenandoah two garbage collectors officially landed
In JAVA 15, ZGC and Shenandoah are no longer experimental functions, officially landed (but G1 is still the default). If you upgrade to a version later than JAVA 15, please try it quickly, with better performance and lower latency
Sealed class
JAVA inheritance can only choose to allow inheritance and not allow inheritance (final modification). Now a new feature of sealed (Sealed) class is added, and certain classes can be specified to inherit:
public sealed interface Service permits Car, Truck {
int getMaxServiceIntervalInMonths();
default int getMaxDistanceBetweenServicesInKilometers() {
return 100000;
}
}
JAVA 16 (March 2021)
JAVA 16 in user-visible place change is not much, basically experimental content of 14/15, to 16 officially released, will not repeat here.
to sum up
The various new features introduced above, some of which are still experimental features in the historical version, but according to the current update frequency of JAVA as the donkey, it is very likely that the next version will be the stable version.
Look at the time, has 300 seconds arrived?
> Originality is not easy, unauthorized reprinting is prohibited. If my article is helpful to you, please like/favorite/follow to encourage and support it ❤❤❤❤❤❤
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。