Debbie Clay

Debbie Clay

1561108026

Java 12 Tutorial: How the new switch expressions work

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

What is GEEK

Buddha Community

Java 12 Tutorial: How the new switch expressions work
Tyrique  Littel

Tyrique Littel

1600135200

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK?

OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE). It contains the virtual machine, the Java Class Library, and the Java compiler. The difference between the Oracle OpenJDK and Oracle JDK is that OpenJDK is a source code reference point for the open-source model. Simultaneously, the Oracle JDK is a continuation or advanced model of the OpenJDK, which is not open source and requires a license to use.

In this article, we will be installing OpenJDK on Centos 8.

#tutorials #alternatives #centos #centos 8 #configuration #dnf #frameworks #java #java development kit #java ee #java environment variables #java framework #java jdk #java jre #java platform #java sdk #java se #jdk #jre #open java development kit #open source #openjdk #openjdk 11 #openjdk 8 #openjdk runtime environment

Samanta  Moore

Samanta Moore

1620458875

Going Beyond Java 8: Local Variable Type Inference (var) - DZone Java

According to some surveys, such as JetBrains’s great survey, Java 8 is currently the most used version of Java, despite being a 2014 release.

What you are reading is one in a series of articles titled ‘Going beyond Java 8,’ inspired by the contents of my book, Java for Aliens. These articles will guide you step-by-step through the most important features introduced to the language, starting from version 9. The aim is to make you aware of how important it is to move forward from Java 8, explaining the enormous advantages that the latest versions of the language offer.

In this article, we will talk about the most important new feature introduced with Java 10. Officially called local variable type inference, this feature is better known as the **introduction of the word **var. Despite the complicated name, it is actually quite a simple feature to use. However, some observations need to be made before we can see the impact that the introduction of the word var has on other pre-existing characteristics.

#java #java 11 #java 10 #java 12 #var #java 14 #java 13 #java 15 #verbosity

Samanta  Moore

Samanta Moore

1621096440

Functions for Strings in Java

In this tutorial, you will learn how to make better use of built-in functions for Strings in Java to program more quickly, effectively, and aesthetically.

What Is a String?

Firstly, of course, we have to initialize our string. What is a string used for?

  • You want to look at your string as a line, not as a mass of symbols.
  • If you have a long text, you want to work with the words, not the letters.
  • If you have lots of information, you need functions that solve questions as quickly as possible.

#java #tutorial #java strings #java tutorial for beginners #java string #string tutorial

Samanta  Moore

Samanta Moore

1621118940

How to Convert ODT Files to PDF in Java

Convert Office Open Document Text File (ODT) to standard PDF, DOCX, PNG, and JPG using Java.

Microsoft has maintained its position in the spotlight for formatted document creation and editing for good reason. Its extreme ease of use and lack of a learning curve has transformed the Microsoft Office Suite into a household name for most computer users in the United States as well as globally. This is propagated further through its almost ubiquitous use in education, as students are raised and taught using these applications.

The issue that arises with these programs, however, is their operation costs. For Apple and other non-Windows-based Operating Systems, the purchasing fees for Office can be steep. This, then, creates a paywall separating potential users from programs to which they are already accustomed. As an answer this problem, Microsoft created the OpenOffice application, which is a free, opensource version of the classic Office Suite. Within this application, you can perform almost all of the same functions as Office Suite, including creating text documents like one would with Microsoft Word. These text documents can be made using OpenOffice Writer, and are formatted using the .ODT file type. While this file type can be opened and saved using OpenOffice Writer and Word, in order to convert the file to a different format such as PDF you will need to run it through a conversion process.

The following APIs will allow you to convert your ODT documents to PDF, DOCX, PNG, and JPG for use in whatever way you need. The goal of this tutorial is to provide a simple and efficient means for instantly converting your ODT files without needing to find or download any extraneous programming.

#java #tutorial #api #pdf #java api #pdf converter #api access keys #api tutorial #java api tutorials #java apis

Samanta  Moore

Samanta Moore

1624948542

Lambda Expression in Java 8

In this blog we will understand what is the lambda expression and why we need lambda expression and how we use lambda and about the functional interface.

What is Lambda Expression :
  • It is an anonymous function.
  • Not having name
  • No return type and no modifiers.

#functional programming #java #functional java #java #java 8 #java8 #lambda expressions in java