Java 14 Features


Java 14 features.
Major features are consolidated here, Please refer below.

No explicit typecasting in instanceof –
Now in instanceof will implicit typecast the variable into given instance if instanceOf return true, refer below code snippet –

if (obj instanceof String) {
    String str = (String) obj; // no need to declare and cast again this object in java 14
    … str.equals(…)
}else{
}

if (obj instanceof String str) {
        … str.equals(…)
}else{
}

Improved NullpointerException logging –
Now NummpointerException will explain more about nullpointer exception, containing line and object details where it get failed.
Refer below code snippet –

obj1.obj2.obj3.obj4 = object; //if obj1.obj2.obj3 is null than exception will like this -
Cannot read field 'obj4' because ”obj1.obj2.obj3” is null.
    at Prog.main(Prog.java:5)


Records(Preview) –
To avoid duplicity in class, a new class syntax will be introduced in preview mode in Java 14. Using records we can remove lots of duplicate code regarding constructors, setter, getter, equals(), hashCode(), toString(), etc

Refer below code –
final class Student {
    public final String firstName;
    public final String lastName;

    public PoString(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

// Above code can re-written using record syntax
record PoString(String firstName, String lastName) { }
Note – Records are implicit Final, can’t be abstract or inherit any other class

No comments:

Post a Comment