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

Related Posts