{{announcement.body}}
{{announcement.title}}

Java 14 Is Here With Features That Will Help the App Development World

DZone 's Guide to

Java 14 Is Here With Features That Will Help the App Development World

In this article, we discuss the new features that Java 14 offers, including Switch statements, text blocks, instanceof pattern matching, and more.

· Java Zone ·
Free Resource

Java 14 was released recently on March 17. It has features that are more useful for mobile app development than older versions, like Java 13 and Java 12. Java is one of the most popular languages with 18.84% share after Python.

Ease of multi-threading, API integration, and in-built security features make Java one of the most sought after programming language for app developers. Most important is its ease of integration of compatibility features that are updated regularly by operating systems. Android 11 releasing this year will have several new compatibility features, which can be easily integrated with Java.

So, let’s see what can we expect with these new features from Java 14.

Switch Expressions

Switch expressions were introduced in Java 12 as a preview feature. They're now permanent in Java 14. But, before we go through the latest changes in switch expressions, let’s understand a few benefits of these expressions in terms of app development.

  • Switch expressions provide an easy to use syntax to reduce bugs.

  • It reduces code verbosity by managing multiple case labels through a single branch.

  • It helps the compiler check for enum values matching Switch labels to keep your apps bug free.

  • A switch can be used as an expression form for compact code with specific intent.

Now, with Java 14, you get all these benefits of switch expressions plus the facilities of lesser bugs, easier syntax, and compact codes. An example of switch expressions for Java 14 is given here.

Java
 




xxxxxxxxxx
1
19


 
1
var log = switch (event) {
2
    case PLAY -> "User has triggered the play button";
3
 
          
4
    case STOP, PAUSE -> "User needs a break";
5
 
          
6
    default -> {
7
        String message = event.toString();
8
        LocalDateTime now = LocalDateTime.now();
9
        yield "Unknown event " + message + 
10
              " logged on " + now;
7
 
          
11
    }
12
 
          
13
};



Text Blocks

If you have trouble managing your multiline string literals, then Java 14 has a solution. Text blocks are not new, but it will be the second preview of the feature with Java 14. In the current version, there are few tweaks that will help mobile app developers.

It is a common practice for developers to write code with several strings. With this feature, developers can escape string sequences and provide several text formats easily. An example of HTML format can be seen here.

Java
 




xxxxxxxxxx
1


 
1
String html = "<HTML>" +
2
"\n\t" + "<BODY>" +
3
"\n\t\t" + "<H1>\"Java 14 is here!\"</H1>" +
4
"\n\t" + "</BODY>" +
5
"\n" + "</HTML>";



As you can see in the following example, text blocks simplify coding and make it significantly more elegant.

Java
 




xxxxxxxxxx
1
11
9


 
1
String html = """
2
<HTML>
3
  <BODY>
4
    <H1>"Java 14 is here!"</H1>
5
  </BODY>
6
</HTML>""";



With text blocks in Java 14, two new escape sequences, \s and \, were introduced. The first escape sequences can be used for single space, while the other can be used for the suppression of newline characters. Such escape sequences help in long line content to be broken into readable text.

With an escape sequence, you can express multiline strings with a text block, as shown here:

Java
 




xxxxxxxxxx
1


1
String text = """
2
    Lorem ipsum dolor sit amet, consectetur adipiscing \
3
    elit, sed do eiusmod tempor incididunt ut labore \
4
    et dolore magna aliqua.\
5
""";



Instanceof Pattern Matching

Eliminate your casts that follow an instanceof in a conditional statement. Let’s take an example of code with instanceof.

Java
 




xxxxxxxxxx
1
11
9


1
if (obj instanceof Group) {
2
  Group group = (Group) obj;
3
 
          
4
  // use group specific methods
5
  var entries = group.getEntries();
6
}


 

With this feature, you can shorten the above code to this.

Java
 




xxxxxxxxxx
1


1
if (obj instanceof Group group) {
2
  var entries = group.getEntries();
3
}



Here, pattern matching features eliminates the need for a repeated statement, indicating that obj is of type Group. This can reduce errors. Another important feature of the pattern matching attribute is its ability to reduce explicit casts with CaseInsensitiveString.

It  can be seen that the earlier code

Java
 




xxxxxxxxxx
1


 
1
@Override public boolean equals(Object o) { 
2
    return (o instanceof CaseInsensitiveString) && 
3
            ((CaseInsensitiveString) o).s.equalsIgnoreCase(s); 
4
}



Can be changed to:

Java
 




xxxxxxxxxx
1


 
1
@Override public boolean equals(Object o) { 
2
    return (o instanceof CaseInsensitiveString cis) &&
3
            cis.s.equalsIgnoreCase(s); 
4
}



The idea behind pattern matching features is to enhance language attributes with easier syntax to extract components of objects. Every condition is a type of check for any instance of an operator. Take an example of an OnlinePayment domain class. There are three fields, Bank name, Payment amount, and date. The components that you need to worry about are:

  1. A constructor.

  2. Getter method.

  3. String code.

  4. hashcode.

Such code needs a huge amount of space for storage and also has multiple components. With Java 14, you can create a very short code, such as this.

Java
 




xxxxxxxxxx
1


 
1
public record OnlinePayment(LocalDate date,
2
                              double amount,
3
                              String BankName) {}



It clearly reduces the code compact, making syntax significantly easier to follow.


NullPointer Exceptions

NullPointerExceptions can cause huge debugging issues. They tend to appear in application logs, during the code being run in production. For example, as you run the following program:

Java
 




xxxxxxxxxx
1


 
1
var name = user.getLocation().getCity().getName();



You will get an error message or code as follows:

Java
 




xxxxxxxxxx
1


 
1
Exception in thread "main" java.lang.NullPointerException
2
 
          
3
    at NullPointerExample.main(NullPointerExample.java:5)



Here, either the user can be null, or the command getLocation() or getCity() can be returning null. Either way, you receive a null exception.

But, with the latest Java 14, you get the following code.

Java
 




xxxxxxxxxx
1


 
1
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Location.getCity()" because the return value of "User.getLocation()" is null
2
 
          
3
    at NullPointerExample.main(NullPointerExample.java:5)



Here, There are two components to look for are:

  1. Location.getCity() becomes mandatory.

  2. User.getLocation() returns null.

Thus, you get to know which components return null and make adjustments by running diagnostics.

Conclusion

Java 14 looks promising for mobile application development. With the above-mentioned features, coding needs are reduced, and faster applications can be created. Easier syntax will allow mobile app developers to render high-quality apps with fewer bugs. It's time to choose Java again and unleash the pure power of programming for app development.

Topics:
app development, instanceof, java, java 14, swtich, text blocks

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}