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 : 2236  
 
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

A beginner’s guide to software vulnerabilities

What are software vulnerabilities The number of devices connected to the Internet is growing every day. And among those devices we find not only computers and smartphones, but also an ever-rising…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

A Java Approach: Selection Structures - Use Cases

Hello everyone and welcome back! Up to now we have been concerned to make as complete an overview as possible of the fundamental concepts we need to approach the use…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

A Java approach: boolean variables

The previous time, we talked extensively about Boolean variables, trying to outline the main operations that can be carried out at a practical level.  Of all the cases examined, we have…

A Java approach: condtional structures

Hello everyone and welcome back! The previous times we have introduced the concept of variable, trying to define some basic concepts about it.  However, some situations suggest that the concept of…

Hashmap: hashing, collisions and first functions

Today we are going to study some concepts closely related to hashmaps. The concepts we are going to see are hashing and collisions. Hashing The idea of hashing with chaining is to…

Hashmap: Overflow Lists

In this short series of articles we will go to see how it is possible to create the Hashmap data structure in C. In the implementation we're going to use the…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

Data structures in Java - Linked Lists

With 2020 we are going to look at a new aspect of programming: data structures. It is often the case that everyone uses structures provided by the various programming languages.…

A Java approach: variables - use case

Hello all friends and welcome back! After the introduction made on the variables, we try to analyse some critical issues that may arise in quite common situations. Let's start by analysing…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration