Java14
Java 14 was released on March 17, 2020. Among the functions added in Java14, I would like to introduce the functions that can be used for writing code.
record(preview)
You can easily create a class for holding data.
public record Customer(String name, String age){}
The equivalent of the following class is created.
public class Customer {
private final String name;
private final String age;
public Customer(String name, String age) {
this.name = name;
this.age = age;
}
public String name() {
return this.name;
}
public String age() {
return this.age;
}
public String hashCode() {...}
public boolean equals() {...}
public String toString() {...}
}
Since the method for setting the value is not defined, the value cannot be changed after the instance is created.
It is now possible to define a character string that includes line breaks. Enclosing a character string with "" instead of "" recognizes it as a text block.
String str1 = "aaaa\n"
+ "bbb";
String str2 = """
aaa
bbb\
"""
The above two strings indicate the same thing. If you do not want to start a new line, enter .
Helpful NullPointerExceptions
You can now get a detailed message when a NullPointerException occurs.
String str = null;
str.length(); // NullPointerException
By default, the following exception is output.
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:5)
In java14, if you execute it with "-XX: + ShowCodeDetailsInExceptionMessages", the following detailed exception will be output.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>" is null
at Test.main(Test.java:5)
You can now define variables of that type while checking the type with instanceof.
Object obj = "obj";
if (obj instanceof String str){
System.out.println(str.length());
}
Recommended Posts