Java 12 Tutorial: How the new switch expressions work

Java 12 Tutorial: How the new switch expressions work

In this article, you'll learn how the new switch expressions work in Java 12

The switch case expressions in Java go back pretty much to the beginnings of the programming language. It was basically a compromise in language design to make it easier for C++ developers to switch to Java. Relics like break and fall-through were not very intuitive and caused a lot of errors. In addition, the case statement was very limited regarding the notation of the values. Fortunately, this all changes with Java 12. The syntax has been slightly modified to allow specifying one expression and multiple values. In this way, case differences can be formulated much more elegantly.

The new switch expressions in Java 12

An example of this new language feature in Java 12 is the mapping of weekdays to their textual length. Let’s first analyze why an extension and modification in the syntax and behavior of switch make sense. What were the previous weaknesses of switch? For clarification, in Listing 1 we will look at how you would formulate the mapping before Java 12.

Listing 1

DayOfWeek day = DayOfWeek.FRIDAY;
 
int numLetters = -1;
 
switch (day)
{
  case MONDAY:
  case FRIDAY:
  case SUNDAY:
    numLetters = 6;
    break;
  case TUESDAY:
    numLetters = 7;
      break;
  case THURSDAY:
  case SATURDAY:
    numLetters = 8;
    break;
  case WEDNESDAY:
    numLetters = 9;
    break;
};

Let’s take a critical look at this source code. First of all, the shown construct is not very elegant and quite long. The multiple specification of values is also rather clumsy. Worse still: A break is needed so that the processing runs without surprises and no fall-through occurs. We also need to set the (artificial) auxiliary variable correctly in each branch. So how can we do this better?

Syntax extensions with Java 12: In Java 12, “switch expressions” have been added as preview feature, which make it much easier to formulate case distinctions. In Listing 2, the intuitive syntax is clearly visible:

Listing 2

public static void switchWithReturnAndMultipleValues();
{
  DayOfWeek day = DayOfWeek.FRIDAY;
 
  int numLetters = switch (day)
  {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY -> 7;
    case THURSDAY, SATURDAY -> 8;
    case WEDNESDAY -> 9;
};
}

This example shows the following syntactical innovations: First, the notation of the case statement changes. In addition to the obvious arrow instead of the colon, several values can now be listed. It is particularly remarkable that we no longer need a break: The instructions behind the arrow are only executed specifically for the case, and there is no fall-through for this syntax. Finally, the switch can now return a value, thus avoiding the definition of auxiliary variables.

Enabling the Java 12 syntax extensions: Since the switch expressions are unfortunately not a final feature, you have to specify the command line parameter -enable-preview when compiling and executing the program.

Java 12: Syntax variants for “switch”

While the mentioned syntax changes alone are a great enhancement, you can enjoy even further improved variants of switch: assignments in lambda expressions and “break” with a return value.

Assignments in lambda: In the first example for the Java 12 syntax, only one value was returned on the right side. However, it is still possible to make an assignment or method calls, of course still without the need for a break (Listing 3).

Listing 3

public static void switchAssignment()
{
  final int value = 2;
  String numericString;
 
  switch (value)
  {
    case 1 -> numericString = "one";
    case 2 -> numericString = "two";
    case 3 -> numericString = "three";
    default -> numericString = "N/A";
  }
 
  System.out.println("value:" + value + " as string: " + numericString);
}

“break” with a return value: Anyone who wants to do a Java certification will certainly appreciate another variant of the syntax. Let’s return to the previous syntax. We now want to map names of colors to their number of letters – shown here deliberately with a small mistake to demonstrate fall-through (Listing 4).

Listing 4

Color color = Color.GREEN;
int numOfChars;
 
switch (color)
{
  case RED: numOfChars = 3; break;
  case BLUE: numOfChars = 4; break;
  case GREEN: numOfChars = 5; /* break; UPS: FALL-THROUGH */
  case YELLOW: numOfChars = 6; break;
  case ORANGE: numOfChars = 6; break;
  default: numOfChars = -1;
}
 
System.out.println("OLD: " + numOfChars);

In this example, you can see the disadvantages of the old syntax, which is a bit cumbersome to use and makes the fall-through hardly visible. The need to define the auxiliary variable is another beauty flaw. Let’s see how Java 12 works better.

Implementation with Java 12: The listing with Java 12 shown below is quite close to the old syntax, but with dedicated improvements: As a rather minimal variation, you can note a return value behind the break. In addition, several values can be listed in case. This results in the more readable variant shown in Listing 5.

Listing 5

public static void switchBreakReturnsValue()
{
 
  Color color = Color.GREEN;
 
  int numOfChars = switch (color)
  {
    case RED: break 3;
    case BLUE: break 4;
    case GREEN: break 5;
    case YELLOW, ORANGE: break 6;
    default: break -1;
  };
  System.out.println("color:" + color + " ==> " + numOfChars);
}

This example shows the advantages of the syntax. Although this is very similar to the previous variant, there are some simplifications and improvements. For one thing, you no longer need an artificial auxiliary variable, but can return a value with break, which stops processing there, similar to the return of a method. Finally, you can now specify multiple values in one case, which allows a more compact notation.

Adjustments for build tools and IDEs

To demonstrate the effects of Java 12 on build tools and IDEs, we use a simple example application with the following directory structure:

Java12Examples
|-- build.gradle
|-- pom.xml
‘-- src
  ‘-- main
    ‘-- java
      ‘-- java12
        ‘-- SwitchExample.java

The methods of the SwitchExample class have already been explained in the previous sections. There we can find some variants of the new syntax of the switch statement.

Java 12 with Gradle: For Java 12, especially for trying out the new syntax with switch, you need a current Gradle 5.1 (or newer) and some suitable information in the file build.gradle (Listing 6).

Listing 6

apply plugin: ’java’
apply plugin: ’eclipse’
 
sourceCompatibility=12
targetCompatibility=12
 
repositories
{
  jcenter();
}
 
// Aktivierung von switch preview
tasks.withType(JavaCompile) {
  options.compilerArgs += ["--enable-preview"]
}

Then we can build a corresponding JAR as usual with gradle clean assemble and start the class SwitchExample as follows: java -enable-preview -cp build/libs/Java12Examples.jar java12.SwitchExample. In both cases, it is important to specify the command line parameter -enable-preview, because this is the only way to start the program.

Java 12 with Maven: For Java 12 you need a current Maven 3.6.0 and the Maven Compiler Plugin version 3.8.0. Then you can enter the information shown in Listing 7 in the pom.xml:

Listing 7

<plugins>
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
      <source>12</source>
      <target>12</target>
 
      <!- - Wichtig für Java 12 Syntax-Neuerungen ->
      <compilerArgs>--enable-preview</compilerArgs>
    </configuration> 
  </plugin>
</plugins>


With these modifications, you can run a Maven build with mvn clean package. Now we want to see the new switch functionality in action and enter the following:

java --enable-preview -cp target/SimpleJdk12Application-1.0.0-SNAPSHOT.jar
java12.SwitchExample

This starts the application as expected.

Conclusion

The joy over the new features in Java 12 is lessened because the raw string literals didn’t make it into the release. While the improvements in the switch-case area are very pleasant, they are almost overdue. Unfortunately, they are only integrated as preview and have to be activated via -enable-preview.

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners

Description
This is the best course to learn to program in Java in Spanish from scratch and without any experience in this fabulous programming language. This is the first course where we will study the Fundamentals of Java, and we will take you step by step until you acquire the bases of the Java language and you can start to study more advanced Java topics.

The content is divided into perfectly structured levels, each level supported by the previous one, with the aim of adding Java knowledge incrementally and so you can focus on mastering the issues little by little and gradually. So ensure the success of your Java training.

We will also offer support for any doubts about the didactic material included in this Java Fundamentals course.

We manage a new teaching methodology that we have called Speed ​​Learning. This methodology consists of concise videos that go directly to the point to be studied, complemented by eBooks with explanations and step-by-step images (which you can print, or search for any text you need, or use for your offline study), since As we know we can not do text search within a video. In addition, our methodology includes perfectly structured and very didactic exercises that will allow you to accelerate your eLearning learning. No loss of time in videos where you have to watch the instructor codify an exercise, too much theory, little practice or anything like that. Our Speed ​​Learning methodology guarantees that in the shortest possible time you will acquire the necessary knowledge for the Java professional and working world.

The Java Fundamentals course includes the following topics for study:

Lesson 1 - Starting with Java Technology

The amazing world of Java programming

What is Java technology (from a practical approach)

Our first Java program from scratch

Lesson 2 - Variables and Operators in Java

Use of Variables in Java and what we use them for

Types of Data in Java and how they are classified

Management and Classification of operators in Java

Lesson 3 - Control statements in Java

Using the if-else structure and where to use it

Handling the switch structure and when applying it

Lesson 4 - Handling Loops in Java

Use of the for loop and its use

Using the while loop and how to apply it

Use of the do-while loop and when to use it

Lesson 5 - Object Oriented Programming

Introduction to Object Oriented Programming (OOP)

Handling Classes in Java

Use of Objects in Java

Lesson 6 - Functions in Java

Declaration of Methods or Functions in Java

Use and call of functions in Java

Lesson 7 - Data Management in Java

Using Arrays in Java

Management of Matrices in Java

Lesson 8 - Inheritance in Java

Inheritance Management in Java

Use of superclasses and subclasses in Java

Final Level Laboratory

Final Exercise where everything learned in this Level is integrated

At the end you get a certificate of having completed the Java Fundamentals course.

We wait for you on the other side.

Ing. Ubaldo Acosta

Founder of Global Mentoring

Passion for Java Technology

Who this course is for:

Anyone who wants to learn how to program in Java
Basic knowledge
Basic knowledge of PC use
Basic management of an operating system such as Windows, Mac or Linux
It is not necessary to know how to program, we will start from scratch !!!
The attitude and desire to start coding and learning Java once and for all from scratch!
What will you learn
Have the basics of the programming language with Java
You will know the basic syntax of the Java language
Manage the concept of Variables and Operators in Java
We will study Object Oriented Programming with Java
You will learn the Control Statements and Loops in Java
We will see the concept of Functions with Java
We will study the concept of Inheritance in Java
We will learn to use Arrays in java
We will handle the concept of Matrices in Java
We will learn to Design Classes in Java
We will make a final application with everything learned in the course
To know more:

Java Essentials : Learn Core Java From Basic to Advance

Java Essentials : Learn Core Java From Basic to Advance

Learn Java Programming Using Practical Assignments. Start Building Back-end Web Applications Robust Test Automation Frameworks By End Of The Course. Learn More!

Description
This is only Java related course and it's great because it covers just the right amount of Java which is needed to leaning programming, java.

This is a comprehensive yet simple course on java programming language and it concentrates on Java programming concepts.

*************************** No Prior Coding Experience Needed ***************************

This course assumes that you have no programming background. If you have some experience then, it's just a bonus point. You have never code, have some experience or have a lot of experience any other programming language, this course is one stop place for you.

Java is one of the most and useful programming languages to learn You can build back-end of web applications and build robust test automation framework. Specially for Selenium WebDriver GUI automation, Java is most popular choice and has the largest community.

Each lecture consist of a video screencast and code files

There are quizzes, homework to test your knowledge

High focus on practice and asking questions

You will also learn coding best practices

Market is never short of jobs in Java programming language, there are ample of jobs in both Java development and Automation Testing using Java.

What are you waiting for? Enroll today and learn the powerful Java language !!!

Basic knowledge
Nothing else! It’s just you, your computer and your hunger to get started today
Java concepts are covered in the course, no experience needed
Windows/MAC computer
What will you learn
You will be able to EXPLAIN, DESIGN and IMPLEMENT efficient java Programs
You will be confident to clear test automation interviews
Understand the concepts of Object Oriented Programming Language
Complete understanding of java
Expert-level knowledge of Java code (+ advanced tips and tricks used by the pros)
Suitable for beginner programmers and ideal for users who learn faster when shown
To learn more:

Fundamentos de Java: Aprende Java desde cero, sin misterios | Simpliv

Fundamentos de Java: Aprende Java desde cero, sin misterios | Simpliv

Fundamentos de Java: Aprende Java desde cero, sin misterios

Description
This is the best course to learn to program in Java in Spanish from scratch and without any experience in this fabulous programming language . This is the first course where we will study the Java Fundamentals, and we will take you step by step until you acquire the basics of the Java language and so you can start studying more advanced Java topics.

The content is divided into perfectly structured levels , each level supported by the previous one, with the aim of adding Java knowledge incrementally so that you can focus on mastering the issues little by little and gradually. So ensure the success of your Java training.

In other offer support of any doubt teaching materials included in this course Fundamentals of Java.

To make matters worse, we handle a new teaching methodology that we have called Speed ​​Learning. This methodology consists of concise videos that go directly to the point to study, complemented with eBooks with explanations and step-by-step images (which you can print, or search for any text you need, or use for your offline study), since as we know we cannot do text search within a video. In addition, our methodology includes perfectly structured and very didactic exercises, which will allow you to accelerate your eLearning learning. Without wasting time on videos where you have to watch the instructor codify an exercise, too much theory, little practice or anything like that. Our Speed ​​Learning methodology guarantees that in the shortest possible time you will acquire the necessary knowledge for the professional and professional world of Java.

The Java Fundamentals course includes the following topics of study:

Level. Java basics

Lesson 1 - Starting with Java Technology

The amazing world of Java programming
What is Java technology (from a practical approach)
Our first Java program from scratch
Lesson 2 - Variables and Operators in Java

Use of Variables in Java and what we use them for
Data types in Java and how they are classified
Operator Management and Classification in Java
Lesson 3 - Control sentences in Java

Use of the if-else structure and where to use it
Management of the switch structure and when to apply it
Lesson 4 - Cycle Management in Java

Use of the for cycle and its use
Use of the while cycle and how to apply it
Use of the do-while cycle and when to use it
Lesson 5 - Object Oriented Programming

Introduction to Object Oriented Programming (OOP)
Class Management in Java
Using Objects in Java
Lesson 6 - Functions in Java

Declaration of Methods or Functions in Java
Use and call of functions in Java
Lesson 7 - Data Management in Java

Using Arrangements in Java
Matrix Management in Java
Lesson 8 - Inheritance in Java

Inheritance Management in Java
Use of superclasses and subclasses in Java
Final Level Laboratory

Final Exercise where everything learned in this Level is integrated
At the end you get a certificate of having completed the Java Fundamentals course.

We wait for you from the other side.

Ing. Ubaldo Acosta

Founder of Global Mentoring

Passion for Java Technology

Who this course is for:

Anyone who wants to learn to program in Java
Basic knowledge
Basic knowledge of PC use
Basic operation of an operating system such as Windows, Mac or Linux
It is not required to know how to program, we will start from scratch !!!
The attitude and desire to start coding and learning Java once and for all from scratch !!!
What will you learn
Have the basics of the programming language with Java
You will know the basic syntax of the Java language
Will handle the concept of Variables and Operators in Java
We will study Object Oriented Programming with Java
You will learn Control Sentences and Cycles in Java
We will see the concept of Functions with Java
We will study the concept of Inheritance in Java
We will learn to use Arrangements in java
We will handle the concept of Matrices in Java
We will learn to Design Classes in Java
We will make a final application with everything learned in the course
To continue: