Java 13 Features

This post is the introduction of commonly used Java 13 features. 

Switch expressions: This is still in Preview stage in Java 13 version. The main difference about switch expressions in Java 12 and Java 13 is the introduction of Yeild in Java 13. 

Yeild is used to differentiate between Switch statements (Java 11 or less) and Switch expressions (Java 12 or more). 

Primarily the new Switch expressions eliminates the need of break statement and also multiple case statements. 

Eliminating the break statement reduces lot of verbosity and no need for developers to remember it whenever they use switch. Accidentally if developers forget about adding break statement, it introduces bugs and deviate application to meet business requirements. So using Switch expressions improves efficiency of the code and increases productivity. 

Earlier multiple case statements introduced lot of boilerplate code. But with introduction of Switch expressions, we can simply group the related things under one case statement which simplifies the code.

Below is the example that shows the use of Yeild statement introduced in Java 13.

Java 12

int numLetters = 0; 
Day day = Day.WEDNESDAY; 
switch (day) 
{
     case MONDAY, FRIDAY, SUNDAY -> numLetters = 6; 
    case TUESDAY -> numLetters = 7; 
    case THURSDAY, SATURDAY -> numLetters = 8; 
    case WEDNESDAY -> numLetters = 9; 
    default -> throw new IllegalStateException("Invalid day: " + day); 
}; 
System.out.println(numLetters);


Java 13

int numLetters = 0; 
Day day = Day.WEDNESDAY; 
numLetters  = switch (day) 
{
     case MONDAY, FRIDAY, SUNDAY -> yeild 6
    case TUESDAY -> yeild  7; 
    case THURSDAY, SATURDAY -> yeild  8; 
    case WEDNESDAY -> yeild  9; 
    default -> throw new IllegalStateException("Invalid day: " + day); 
}; 
System.out.println(numLetters);

Text Blocks (Preview)

These are used for multi-line Strings such as embedded JSON, XML and HTML etc
Earlier to embed JSON or XML we do the following

String JSON_STRING = "{\r\n" + "\"Name\" : \"Malathi\",\r\n" + "\"Profession\" : \"Software Engineer\"\r\n" + "}";

Now lets write the same JSON using Text Blocks

String TEXT_BLOCK_JSON = """ { "name" : "Malathi", "Profession" : "Software Engineer" } """;

So with Text blocks there is no need to write double quotes or to add a carriage returns. IT is much simpler to write and easy to read and maintain.

There are some other enhancements in JVM, re-implemented Legacy Socket API and so on.
Please note in this tutorial, i just addressed common features which will be used by developers in their day to day lives.

Thank you!

Comments

Popular posts from this blog

Bash - Execute Pl/Sql script from Shell script

Gradle Fundamentals

Load Balancing using Spring Cloud Netflix Ribbon