Wednesday, April 1, 2020

Java 14 New Features

Oracle Java 14, Oracle Java Tutorial and Materials, Oracle Java Cert Exam

Oracle has released a new version of Java named Java 14, which includes lots of new features, improvements in tooling, security, debugging, and updated documentation. However Oracle also provides you with the older version of Java as backward compatibility so your previous code can still run on older versions, and it’s not that Java 14 has an entirely different syntax as compared to Java 8 or 9, it’s just the new version that comes with some improvement of previous one.

Though many developers would kick the update of their Java SE or JDK into the long grass, it’s always suggested to update your tools with time. However, the new update does not bring too many things for a beginner developer, but updates always have an impact on big projects, which include too many java files with thousands of lines of code.

1. Download Java 14


You can visit the official website of Java to download Java JDK 14, or you can click on this link; this would also lead you to the download page.

You can also download any Java IDEs to write code for the new version of Java. All the popular updated Java IDEs such as IntelliJ IDE and Eclipse support Java 14.

2. What’s New in Java 14?


Java 14 documentation officially addresses more than 15 new enhancements or changes, which include the Java language support and the latest APIs for the JDK.

2.1 Switch Expression (JEP 361)

However, the classical C++ or C like Switch Statement was already in Java, the new switch expression with some new features and options was introduced as a preview in Java 12 and 13, but now we can say that it is a standard in Java 14.

Let’s see with an example, how we used to use the Switch Statement before Java 12

tags.switch (day) {
 case 1:
   System.out.println("Let's meet!");
   break;
 case 2:
   break;
 case 3:
   System.out.println("Let's meet!");
   break;
 case 4:
   break;
 case 5:
   System.out.println("Let's meet!");
   break;
 case 6:
   break;
 case 7:
   System.out.println("It's Sunday we cannot meet today");
   break;
  }

The issues with this syntax of Old Switch Statement:

◉ Here we have the same behavior for Case 1, Case 3, and Case 5, but we have to define a specific case for each one, which means the Java switch statement does not provide a compact way to write similar behavior.

◉ With each switch case statement, we have to put the break statement; if we don’t, then the code would fall through.

2.2 Java 14 Switch Expression Arrow Operator

With Java 14, we have a new syntax for Switch statement, which is known as Switch Expression, and here we got a new operator Arrow -> which helps to eliminate the break statement, and provides a compact and legible look to the switch Expression.

The Syntax for Arrow Operator:

case identifier -> statement;

or

case identifier -> {// statement block ;}

Switch Expression for Java 14 (Arrow Operator)

Let’s rewrite the above Switch Statement with new Java 14 Switch Expression:

switch (day) {
 case 1, 3, 5 -> System.out.println("Let's meet!");
 case 2, 4, 6 -> {
       // Do nothing
 }
 case 7 -> System.out.println("It’s Sunday we cannot meet today");
 default -> "Not valid";
 }

Here you can see that with the help of Java 14 arrow operator, we eliminated the break statement, and here using a single line, we have passed a similar behavior for different cases.

2.3 Java 14 Switch Expression yield Operator

In Java 14, the switch statement has a keyword known as yield, which acts as a return keyword to the case statement expression and this feature of switch statement makes it a switch expression in Java 14:

yield Syntax:

case -> {yield value;}

Switch Expression for Java 14 (yield statement):

String message = switch (day) {
 case 1, 3, 5 -> "Let's meet!";
 case 2, 4, 6 -> {
   yield "No meeting today";
 }
 case 7 -> {
   yield "It's Sunday we cannot meet today"; }
 default -> "Not valid";
};

Here the switch statement would yield a value, and that value would store in the message. We should always cover the possible value for a switch statement, and for that, a switch expression should always have a default statement that covers the illegal cases.

Oracle Java 14, Oracle Java Tutorial and Materials, Oracle Java Cert Exam
2.4 Text Block (JEP, 368):

It is a new feature in Java 14; however, its preview has already been introduced in Java 13. In the old version of Java when we have a long string, and we want to put a newline between the string, we had to use the “  \n ”  newline escape character, and writing a single long string is also not good looking. Java 14 provides an alternative way to write a string in a multi-line with a compact core.

The old version of Java with string:

String old_java = " This is first line\n" + "This is second line" + "and this is third line\n";

Java 14 Text block:

To write long multi-line string in Java we use the Text block here the string resides in 3 double inverted quotations """ """.

Example:

String new_java = """
     This is the first line
     This is Second Line
     and this is the third line
     """;

Here each space and new line you give in between the characters will also be shown in the output.

2.5 Java 14 Pattern Matching, for instance (JEP 305)

The instanceof statement was already present in the older versions of Java, but Java 14 provides a technique in which we can typecast the string object into another string variable using a single line rather than using multiple lines.

Older version of Java with Typecasting using instanceof:

Object object_string = "It is a string, but is treated as an object...";
    if (object_string instanceof String)
{
    String stringObject = (String) object_string;
    System.out.println(stringObject.length());
}

Java 14

Object object_string = "It is a string but it treated as an object...";
    if (object_string instanceof String stringObject)
{
    System.out.println(stringObject.length())
}

Now we do not need to write an extra statement for the type conversion explicitly; the enhancement of instanceof statement in Java 14 can type converge of a new variable simultaneously within a single line.

2.6 Records (JEP, 359):

It is a preview mode in Java 14, and we can expect the complete standard form in Java 15. Suppose if we want to create some way to represent a Student detail, for this, we can create a  Student class with some data variables such as Name, age, and grades.

class Student
{
  public final String name, grades;
  public final int age;
}

But here we don’t need getter and setter; instead, we will create a constructor. It’s a good practice to create a constructor, and with the help of it, we can also tell that if two Student objects refer to the same Student.

class Student {
   public final String name, grades;
      public final int age;
           public Student(String name, int age, String grades)
                  {
                          this.name = name;
                          this.age = age;
                          this.grades = grades;
                  }
   @Override
   public boolean equals(Object o)
    {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Student student = (Student) o;
    return Objects.equal(student.name, name) == 0 &&
        Objects.equal(student.grades, grades) == 0 &&
        Integer.compare(age, student.age);
    }
   @Override
       public int hashCode()
  {
    return Objects.hash(name, age, grades);
   }
   @Override
   public String toString()
   {
    return "Student{" +
        "name=" + latitude +
        ", age" + longitude +
        ", grades='" + grades + '\'' +
        '}';
 }

In the above code, our main focus is on the student detail, which are name, age, and grades, but we have overridden the methods like constructor, hashcode, equals, and toString, but Java 14 provides a preview feature record which can resolve such kind of boilerplate.

record Student(String name, int age, String grades){}

Here the constructor, hashcode, equals, and toString will be generated by the compiler, and you can save much unnecessary overriding of code.

2.7 Helpful NullPointer Exceptions(JEP 358)

It is a new feature that has been added to Java 14. The Java Virtual Machine throws an exception, which is known as NullPointerException(NPE), and this exception occurs when the code tries to dereference a null reference, and it is one of the most common exceptions in Java.

obj.sec_obj.val = 10;

Exception:

Exception in thread "main" java.lang.NullPointerException
    at Npe.main(Npe.java:17)

This example was compiled on the older version of Java, and here you can see that the error message does not provide any specific information which reference is null, it could either be obj or obj.sec_obj.

But Java 14 addresses this problem and provides a better error message to debug this statement.

tags.obj.sec_obj.val = 10;

Output:

Exception in thread "main" java.lang.NullPointerException:
       Cannot read field "val" because "obj.sec_obj" is null
    at Npe.main(Npe.java:17)

Now with the new exception information, we can directly visit the sec_obj section of the code and debug the problem.

Related Posts

0 comments:

Post a Comment