The release cycle of Java has changed quite dramatically recently, meaning we’re getting new features at a more rapid pace than earlier. If you still hadn’t had the time to read up on what’s been going on the last releases, look no further!
We’ve previously coveredwhat’s new in Java 11, and today I want to tell you a little bit about what has happened since then. Please beware that none of these versions are LTS (long term support) versions. So if you’re not absolutely sure you’ll be able to upgrade every six months until Java (is released, you might want to stay put on Java for your most critical applications.
With that disclaimer out of the way, we can jump into the good stuff. I wont coverallnew features (have a look at the JEP list for versionand************************************if you ‘d like), but I’ll highlight a few interesting language features.
Today I’m focused ontwonew features, another post with some additional features will be available in a couple of days.
Switch enhancements
switchhas gotten some changes ! They have been previewed in JDK and again in and are at time of writing aimed for release in JDK (********************************************************. We’ll be getting one new feature for when
switch
is used as a statement and, in addition, it can also be used as an expression going forward.Arrow labels
We can now use arrow labels (
case X ->) in addition to the old
case X:label in
switch
switch
statements. Upon using arrow labels, only the expression or statement on the right hand side of the arrow will be executed. This means there will be no fall through) so you no longer need to rememberbreak;
:(String) **************** (quantityString
;switch(
n
){ (1)->(quantityString) **********************=“one”**************************************** (2)
->(quantityString) **********************=“two”**************************************** default ->quantityString
=“many”**************************Switch expressions
switchcan now be used as expressions, ie it can return a value. This means we won't have to first declare a variable, then assign a value in every single branch. Combined witharrow labelsit allows us to express our intent in much fewer lines of code:
(String) **************** (quantityString=(1)switch (( (k) ){->“one” (2)->“two” default ->“many”;Sometimes you might be forced to execute a code block as part of a case expression. In order to combine this with arrow label syntax, you must
yield
a value at the end of the block:
(DayType) *********************** (type
=switch (( (day) ){(1),(2) (**********************,(3) **************************************************4******************************5******************->WEEKDAY; (6)
,
(7) ->(WEEKEND) default -> {**********************) loggerwarn ****** (day***"is not a valid day. Legal values are [1..7]");yield UNKNOWN;You may also turn
switch
es using the old style labels from statements to expressions by using
yield
.**************** (type
=switch (( (day) ){(1),(2) (**********************,(3) **************************************************4******************************5***************************************** yield WEEKDAY
(6)
,
(7): yield WEEKENDdefault:logger
****** (daywarn***“is not a valid day.” ()
yield UNKNOWN;⚠️ Please remember that it is the arrow label syntax that preventsfall through. That means, if you forget to
yield
, the next case expression will be evaluated and you might end up with the wrong result. I'd recommend you stay away from this syntax for this reason.
As usual more features leads to more complexity. We've certainly gotten a more feature rich
switch
, but as illustrated above it has also become much more complex. You have to remember which label style,
:
or ->, hasfall through- and what was the point of
yield again? Stephen Colebourne (you know, that guy who wroteJoda-Time) has writtena much more in depth blog postwhere he raises some important questions regarding the UX of these features. If you're interested in the new
switch
features, make sure to read this first! Pattern matching for
As a Java developer you've most likely been in a situation where you have to check if an object is a certain type, and if it is - cast it to that type. This pattern is widely used in e.g.
equals
implementations.
Introduced as a preview feature in JDK 90,instanceof is extended to take what's called atype test patterninstead of just a type. Atype test patternconsists of a predicate and a binding variable.
laimer Disclaimer: This feature is currently not supported by IntelliJ. You can follow the progress in Jetbrain's issue tracker
.
Consider the following example:
Over Overide
publicboolean
equalsObjectobj************if( objinstanceofPerson{ Personother=Person****************** (obj) **********************;
return
thisname==other
********************** (name) **********************; **************************
return
false **************************Using this new feature, you may rewrite as follows:
Over Overide
publicbooleanequalsObjectobj************if( objinstanceofPersonother********************return
thisname==other
********************** (name) **********************; **************************
return
false **************************In the above example
Person otheris thetype test pattern.
Inside the
if
block, you may use
other
and it's guaranteed to be a Person.
other
is, however,notaccessible outside the
if block.
⚠️ It's worth noting that the scope of a binding variable is determined by the semantics of the containing expressions, which might lead to some surprising results:
(if ****************** *********************** (
()objinstanceofStrings){System
out.println********** (s)**************************else{ Systemout.println********** (s)************************************************************************ obj************ (isnotaString, (sis some other variable in scope (eg a member of the enclosing class). (**********************************objis a****************, s) ****************** (isobj
(cast toString**************************************************************************** (release (
This is certainly not the. most game changing feature in itself, but it sends a signal that Java is embracingpattern matchingas a concept, a language feature many other popular languages has supported for a long time. And as an added bonus, your
equals
implementation can be shortened slightly to emphasize the important bits.Enabling preview featuresThe new
switch
changes currently havepreviewin the most recently released JDK version (). This means you probably don't want to use them to a large extent in the code base you earn your living of. APIs could change, and there is still a chance the feature won't be promoted to a stable feature in its current form.It is, however, valuable to experiment with them. Trying new features is a good way to broaden your skill set, and if there is something you strongly dislike about the usability of a feature you can even provide feedback to the JDK developers. Look for theDiscussionlabel on a feature's JEP page (linked below) to find the correct mailing list.
To get started experimenting with preview features in the tool you use, follow the guides below:
MavenTo activate during compilation, add the following configuration to maven-compiler-plugin (*******************:
**************configuration******************************************release>****************compilerArgs> --enable-preview****************compilerArgs>****************configuration>For test execution, add the following configuration tomaven-surefire-pluginand / ormaven-failsafe-plugin
:**************
configuration******************************************argLine>- enable-preview********************************************************************configuration>Gradle
Enable the compiler flag for compilation and test execution as follows:
(********************** compileJava{optionscompilerArgs=test {{************************) jvmArgs- enable-preview '**************************IntelliJGo toProject Settings>Project
and find theProject language leveldropdown. If you previously targeted version and want to enable the preview features, choose****************************************** (Preview) (************.(*****************************************
(********************************************************************************** (Read More) (****************************************************************************************** ()
GIPHY App Key not set. Please check settings