Java 12, finally less verbose?


We all know Java for its characteristics thanks to which, despite more than 20 years have passed since the first version, it is still one of the most studied and most used languages, despite the growing diffusion of Python.

However, one of the biggest flaws is the fact that it is very verbose and for years Oracle has not shown any signs of change. Finally, with version 12 something seems to change. Java seems to be moving towards a way of programming that, in a future that still seems far away, allows us to write more compact code without losing legibility and above all maintaining the portability that has always characterized this language.

Let's see some important news.

Switch expression improvements

The foundamental thing that must be said is that this feature has been introduced as an experimental function in JEP 325, which means that even if the implementation is complete and working, may not be confirmed int the next versions.

What are the foundamental news?

  • Using break for every case is not necessary anymore;
  • Different constants can be used for the same case;
  • The default case is compulsory;
  • The break instruction can be used to return the switch values;

Let's look at an example:

String season= "";
switch (month) {
case "March":
case "April":
case "May": {
stagione= "Spring";
break;
}
case "June":
case "July":
case "August": {
stagione= "Summer";
break;
}
};

While now, with the new syntax, the code becomes: 

String season=switch(month){
     case "March", "April", "May":{
          break "Spring";
     } case "June", "July", "August":{
          break "Summer";
     }default ->{
          break "Other season";
     }
};

This new way of writing switch expressions could be very comfortable.

New way to compare files: File.mismatch()

The method signature is:

public static long mismatch(Path path, Path path2) throws IOException

The idea is to return the distance between the two files, returning -1 if the two files are the same. Two files can be different when:

  • There are some different bytes, then the position of the first different byte is returned;
  • The file size is not the same, then the minor is returned;

Is this useful? Absolutely yes!

Compact number notation

Veongono introdotti nuovi metodi per la notazione compatta dei numeri a seconda del locale scelto.

New method for the compact number notation depending on the locale chosen are introduced.

public class CompactNumberFormatDemo
{
private static void exampleCompactNumberFormatting(final long numberToFormat){
final NumberFormat nfDefault = NumberFormat.getCompactNumberInstance();
final NumberFormat nfItShort =  NumberFormat.getCompactNumberInstance(Locale.ITALY, NumberFormat.Style.SHORT);
final NumberFormat nfItLong = NumberFormat.getCompactNumberInstance(Locale.ITALY, NumberFormat.Style.LONG);
final NumberFormat nfFrShort = NumberFormat.getCompactNumberInstance(Locale.FRANCE, NumberFormat.Style.SHORT);
final NumberFormat nfFrLong = NumberFormat.getCompactNumberInstance(Locale.FRANCE, NumberFormat.Style.LONG);
out.println("Number to format '" + numberToFormat + "':");
out.println("tDefault:  " + nfDefault.format(numberToFormat));
out.println("tIT/Short: " + nfItShort.format(numberToFormat));
out.println("tIT/Long: " + nfItLong.format(numberToFormat));
out.println("tFR/Short: " + nfFrShort.format(numberToFormat));
out.println("tFR/Long:  " + nfFrLong.format(numberToFormat));
}
public static void main(final String[] arguments)
{
exampleCompactNumberFormatting(15000);
}
}

We will obtain:

Number to format '15000':

Default:  15K
IT/Short: 15.000
IT/Long:  15 mila
FR/Short: 15 k
FR/Long:  15 mille

Teeing collector

The basic principle is similar to the tee command, familiar to unix users, that redirects the input to the two collectors before merging their results using a Bi-function.

var result = Stream.of("Andreas", "Antonia", "Lucia",
"Francesco").collect(Collectors.teeing(
// primo collector
Collectors.filtering(n -> n.contains("c"), Collectors.toList()),
// secondo collector
Collectors.filtering(n -> n.endsWith("s"), Collectors.toList()),
// merger Bi-function
(List
list1, List
list2) -> List.of(list1, list2)
));
System.out.println(result); // -> [[Lucia, Francesco], [Andreas]]

JEP 305: Pattern Matching for instanceof (Preview)

Finalmente non è più necessario effettuare il casting esplicito prima di usare un oggetto prima di poterlo utilizzare.

Making an explicit cast is not necessary anymore before using an object.

	// Before java 12 
if (obj instanceof String) {
String s = (String) obj;
// use s as a string
}
// In java 12 and maybe then...
if (obj instanceof String s) {
// using s as a string is possible without any explicit cast
}

Other news

  • New method has been added to the String class.More information can be found on the official documentation :
    • indent(int n);
    • transform(Function f);
    • Optional describeConstable();
    • String resolveConstantDesc​(MethodHandles.Lookup lookup);
      ​​​​
  • With JEP334 a new class java.lang.constant has been introduced. It contains the nominal descriptors of various types of constants.

Java seems to be moving towards a syntax that will make the code easier, even if the most interesting features are still a preview. Personally, I am so curios to follow the developements of this version.

I wouldn't have kept the use of variables var, used from java 10. This variables allow the programmer not to define a specific variable type, a little bit like JavaScript. Despite of this, I recognize that sometimes they could be useful, even if they can be used only as local variables. Nowadays Java continues not to interpret var as a keyword, therefore a word dedicated to language, but it still recognizes its meaning. Who knows, maybe with the passage of time and generations of programmers, the use will become more frequent and will become a keyword.

Dealing with dates, what are the dates that concern with the various releases?

  • 13/12/2019 First distribution phase
  • 17/01/2019 Second distribution phase
  • 07/02/2019 Beta version release
  • 19/03/2019 General availability

Is it worth switching to Java12?

In my opinion, absolutely yes! Expecially for the programmers that want to try new features as soon as possible. Personally, I would do the upgrade again a thousand times! I found out some improvements, maybe due to the garbage collector algorithm change, called Shenandoah that doesn't take care of the heap dimension.

Quite the opposite, for beginners it might be convenient to start with the previous version, which is certainly more stable and has no degree differences. When the version becomes stable with the various definitive features, it will certainly be interesting to upgrade.

Enjoy your programming experience with Java! wink

 
by Alessio Mungelli Date: 10-10-2019 java jdk developing programming jdk12 software programmers tutorials explanation whatsnew hits : 5672  
 
Alessio Mungelli

Alessio Mungelli

Computer Science student at UniTo (University of Turin), Network specializtion, blogger and writer. I am a kind of expert in Java desktop developement with interests in AI and web developement. Unix lover (but not Windows hater). I am interested in Linux scripting. I am very inquisitive and I love learning new stuffs.

 
 
 

Related Posts

How to upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

How to record TV programs using VLC

VLC is much more than a simple media player. Behind its simple appearance, there are a lot of features, such as the ability to convert videos to audio format, repair…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

Clicky