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");



              case PERSON_B:

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



              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



1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.