Friday, May 30, 2014

Switch Case using String in Java

Switch case in Java using string values is a little tricky. The concept seems so simple when we think of a logic, only to surprise you later that it is not so simple and it seems like an impossible stuff. It has happened to me multiple times during different time periods with fairly distant gaps that I tend to forget this experience only to be stuck with it again and remember that this has happened to me before like a De-ja-vu.

 

I knew that that switch statements accepts integers, characters and enum types as input parameters. My exploration and try outs with enumeration helped me come up with an idea to use string values in Switch-case statement in a slight indirect way.

 

Following was my attempt and I am happy that I did it J

 

public class EnumTest {

 

       public static void main(String args[]) {

 

              String testName = "PERSON_B";

 

              NameConst name = NameConst.valueOf(testName.toUpperCase());

 

              switch (name) {

              case PERSON_A:

                     System.out.println("Big Brother");

                     break;

 

              case PERSON_B:

                     System.out.println("Small Brother");

                     break;

 

              default: // do nothing or your default logic

 

              }

       }

 

}

 

enum NameConst {

       PERSON_A("Person_A"), PERSON_B("PERSON_B");

 

       private String nameValue;

 

       private NameConst(String nameValue) {

              this.nameValue = nameValue;

       }

}

 

I obtained the following output in my console and am more than happy to see this work J

 

>>Small Brother

 

 

No comments:

Post a Comment