JDK 7 had a lot of list of enhancements. One of it was use of string in a switch statement. In this post we will see how to use String in a switch statement.
We will first see how we needed to code prior to JDK7, when String was not used in the Switch Statement.
Use of If Else instead of Switch prior JDK 7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public void printSalaryByDesignation(String designation){ if("Junior Developer".equals(designation)){ System.out.println("Salary of Junior Developer is $4000"); }else if("Developer".equals(designation)){ System.out.println("Salary of Developer is $5000"); }else if("Senior Developer".equals(designation)){ System.out.println("Salary of Senior Developer $6000"); }else if("Tech Lead".equals(designation)){ System.out.println("Salary of Tech Lead is $7000"); }else if("Manager".equals(designation)){ System.out.println("Salary of Manager $8000"); }else{ System.out.println("Error::No designation found."); } } |
Now we will see using JDK 7 how we can simplify the above code using Switch Case
Use of String in a Switch Statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public void printSalaryByDesignation(String designation){ switch (designation) { case "Junior Developer": System.out.println("Salary of Junior Developer is $4000"); break; case "Developer": System.out.println("Salary of Developer is $5000"); break; case "Senior Developer": System.out.println("Salary of Senior Developer $6000"); break; case "Tech Lead": System.out.println("Salary of Tech Lead is $7000"); break; case "Manager": System.out.println("Salary of Manager $8000"); break; default: System.out.println("Error::No designation found."); } } |
Using a String in a Switch Statement is obviously not a very great enhancement as compared to the other enhancements that are been added in JDK 7.
One of my favorites is Try-with-resources Statement
Please do let me know if the post was helpful.
You can also see the list of JDK 7 enhancements Here