As String has so much importance in java, this decision is widely popular with Java community. This feature was requested by many developers from around 15 years.A switch with String cases is translated into two switches during compilation and there is a debate going in the community that this will add slowness compared to other decision blocks.It might be faster to just use If-Else-If instead of a hash for a string based switch.
The switch statement when used with a String uses the equals() method to compare the given expression to each value in the case statement and also case-sensitive - will throw a NullPointerException if the expression is null. So, it is advisable to check for null before using it in switch() to avoid any possible null pointer exception.
How to use string in switch - Java example :
public class StringInSwitchJava { public static void main(String[] args) { getMonth("FEB"); getMonth("NOV"); } public static void getMonth(String key) { switch (key) { case "JAN": System.out.println("I am January"); break; case "FEB": System.out.println("I am February"); break; case "MAR": System.out.println("I am March"); break; case "APR": System.out.println("I am April"); break; case "MAY": System.out.println("I am May"); break; case "JUN": System.out.println("I am June"); break; case "JUL": System.out.println("I am July"); break; case "AUG": System.out.println("I am August"); break; case "SEP": System.out.println("I am September"); break; case "OCT": System.out.println("I am October"); break; case "NOV": System.out.println("I am November"); break; case "DEC": System.out.println("I am December"); break; } } }
Output:
I am February
I am November
No comments:
Post a Comment