New Language Features in JDK7

New Language Features in JDK 7 

This blog series will cover some of the new language features available in Java7.  To start with, lets cover some changes that are available under the pseudonym "
Project Coin" or in the Community parlance JSR334.The main theme of "Project Coin" according to its Spec Lead Joseph Darcy is "making things programmers do every day easier".

Since Project Coin itself contains a number of small language changes, lets look at them one at a time. The first language change we will be discussing is called "Strings in Switch".


Strings in Switch

To understand this language feature, lets look at a simple use-case - a method that checks the input and prints the matching color.

Prior to Java7, there were generally 2 options available to achieve this. Lets look at them one by one:

 

Option 1:

This the most obvious and simple way of using multiple if-else blocks to check and validate the input.

      public static void oldstyle(String color){
         if(color.equals("RED"))
                  System.out.println("Color is RED");

        if(color.equals("BLUE"))
                  System.out.println("Color is BLUE");
        if(color.equals("YELLOW"))

                  System.out.println("Color is YELLOW");
    }

Option 2 :
For the slightly brave hearted, the other option available was to create an enum to hold the options


Then switch on the enum


 This code is a lot more verbose and inflexible in that both the enum and switch statements need to be updated when ever a new element needs to be checked.


Java7 style:

With Java7, the code looks like this


As you can see, there are no intermediate variables (read enum) to store the data to be compared nor are verbose if-else loops for conditional branching.

Further Reading:

Comments

Popular posts from this blog

From API Keys to Local Power: Run Your CrewAI Agents Offline

The Talent Gap Myth: How Traditional Engineers Evolve in the GenAI Era

Traditional AI vs. Generative AI: Same Foundations, Different Language