Features from Java-7 that you will love being a developer

The latest update to java i.e Java 7 which was launched a few days back. So as a developer , I was pretty curious to know about the changes made with this version of update. Since this update included mostly enhancements and bug fixes, here is the list of changes that I found useful.

1.) Strings in switch
A very essential feature that was in demand for the last two decades is finally introduced in Java SE 7. So it is possible to use switch/case statements for String along with the previously accepted Enums and Integers.
A very basic example to understand the use of switch with Strings.

Example:
String name = "Shivang"
switch(name) {
case "Saurab":
           proceedAhead();
           break;
case "Vishesh":
          proceedAhead();
          break;
case "Shivang":
          proceedAhead();
          break;
default:
          defaultCase();
}


So this was a simple example of the new Java SE 7 feature. In the previous version you would get a compile time exception("Incompatible Types. Require int instead of String") for the code written above.

Things to keep in mind while using switch with Strings.
  • Always perform a null check before the switch statement. In the above example if variable 'name' contains a null reference then you will get an NPE(Null Pointer Exception).
  • Since change in case leads to totally different value in String, there should be a proper check on case of String values.


Behind the scenes
We all know that switch statements are alternatives to nested if-else statements. But they are far more optimitized then a simple set of if-else statements. Still I won't say using switch statements will always give the most optimized code. There are a number of ways that can help you to write a better code than simply using switch/case statements.
So now the question that arises is how is this feature implemented in Java SE 7. So it is nothing but the mixture of hashCode, equals() and the previous version of Switch statements. So in the below example I have used the technique that is used current implementation of this update.

Here we have used simple switch statements using integers. We all know that hashCode of any string gives an integer value. So we used 'hashCode of string' in switch since  there is a support for switch between integers in previous versions of Java SE.
 Since I have mentioned earlier that the null check is must for the switch statements for Strings,  name.hashCode() will lead to NPE if name is null. Now if the hashCode of the two strings is found equal, then it compares the both strings with equals method. And a valid result confirms that the two strings are equal and the instructions associated with that case gets executed. 

Advanced Example:
boolean fall_through = false;
boolean defaultCase = false;
String name;
label outOfSwitch:    {
       switch(name.hashCode()) {  // This statement will lead to NPE in case name is null

       case "Saurab".hashCode():
              // This statement will lead to NPE in case name is null
             if(!fall_through&&!name.equals("Saurab"))   {  
                       /* This is the case where the hashCode is equal but still the string fails the equals method.
                           So the statements for default case are executed*/
                       defaultCase = true;  
                       break outOfSwitch;
               }
              else   {
              proceedAhead();
              fall_through = true;    // So now the code falls through to the next case.
              }

      case "Vishesh".hashCode():
             if(!fall_through&&!name.equals("Vishesh"))   {  
                   /* This is the case where the hashCode is equal but still the string fails the equals method.
                       So the statements for default case are executed*/
                   defaultCase = true;  
                   break outOfSwitch;
             }
            else   {
             proceedAhead();
             fall_through = true;    // So now the code falls through to the next case.
             }

     case "Shivang".hashCode():
             if(!fall_through&&!name.equals("Shivang"))   {  
                      /* This is the case where the hashCode is equal but still the string fails the equals method.
                         So the statements for default case are executed*/
                     defaultCase = true;  
                     break outOfSwitch;      
             }
            else   {
             proceedAhead();
             fall_through = true;    // So now the code falls through to the next case.
             }

      default:
                 defaultCase = true;  
                   break outOfSwitch;
      }
}
if(defaultCase)   {
 /* Execute the default Case statements */
}

In the above examples two flags are maintained (fall_through and defaultCase). So if the fall_through gets true in any case means there is no need to execute the equals method of the remaining cases. And defaultCase gets true when it breaks out of switch statements and executes the instructions associated with the default case.

Related

java 1078333925832103472

Post a Comment

  1. That's a nice feature, but I was expecting more than just one.

    ReplyDelete
  2. @Radmobile: Thanks for you interest in my post. I am not complete with the post yet. I will definitely add other features within a couple of days

    ReplyDelete
  3. Who needs 'switch' if we have polymorphism?

    ReplyDelete
  4. I like the idea behind this post and I would like to see more. It will make a good mini-series especially if you continue to add good examples. I would suggest each post include code and maybe a test case to exercise it.

    ReplyDelete
  5. @Ivank2139 Glad you like the post.Thanks for your valuable suggestions. I will take care of them.

    ReplyDelete
  6. Nice piece of information. I would rather love to read other features too.

    ReplyDelete
  7. Welcome to 2001 in any other language

    ReplyDelete
  8. if(name in ["Saurab", "Vishesh", "Shivang"]) proceedAhead()
    else defaultCase()

    As anonymous points out why is this cool when we have polymorphism or languages with better constructs to express the same thing?

    ReplyDelete
  9. @Anonymous: Yes you are absolutely right. You can use polymorphism here but what if you have something like this?

    switch(name) {
    case "Saurab":
    doFirstTask();
    proceedAhead();
    break;
    case "Vishesh":
    doSecondTask();
    proceedAhead();
    break;
    case "Shivang":
    doThirdTask();
    proceedAhead();
    break;
    default:
    defaultCase();
    }

    I don't say polymorphism cannot be used in this case. Nor can i guarantee this is the most optimized code as I have mentioned in my post.
    There are some cases where if-else-if works faster then 'switch on anything'.

    Using Polymorphism is a good idea. It is more managed and standard way of doing things which really helps when we need to upgrade the code.

    But switch can be better option than if-else-if in some helper classes with static methods. And String being immutable fetching the hash code and switching with the help of indexed Table can be a fast approach too.

    I have always found the topic 'Polymorphism vs Switch' interesting. But after the release of Java 7 the spiciness has been added to this topic.
    I may not have been able to clear things up here but I will soon write a post on "Polymorphism vs Switch".

    ReplyDelete

emo-but-icon

 

Recent Posts

comments

Join Us

 

Recommended

item