switch
in Java was always considered not particularly useful prior to Java 5. In Java 5, enum
was added to the language. This made it more useful to use switch
statements, but was still incomplete. A feature request that has been long in waiting is the ability to use a String
in a switch
.Finally, in Java 7 SE we get the ability to use a
String
in a switch
statement. This feature, I believe, will make the use of switch
more prevalent in code which is post JDK 6.The example below was developed using NetBeans 7.1 Beta on Oracle Solaris Express 11. The NetBeans Java project is located here: StringSwitch.zip.
This code was presented at the Greenville Java Users Group. The Unicode has a hidden message which is displayed when run.
StringSwitch.java
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | /* * Copyright 2011 Blue Lotus Software, LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.bluelotussoftware.example.jdk7; /** * <p> * This is an example application that demonstrates the new JDK 7 feature for * Strings in switch statements. You need to run it to decipher the unicode * value. * </p> * * @author John Yeary <jyeary@bluelotussoftware.com> * @version 1.0 */ public class StringSwitch { /** * @param args the command line arguments */ public static void main(String[] args) { String[] values = { "people" , "tuna" , "orange" , "goldfish" , "rabid hampster" , "the device" , "JDK7" }; StringBuilder sb = new StringBuilder(); for (String s : values) { switch (s) { case "goldfish" : { sb.append( "\u0055\u0073\u0065\u0072\u0073\u0020" ); break ; } case "the device" : { sb.append( "\u0069\u0073\u0020" ); break ; } case "tuna" : { sb.append( "\u0047\u0072\u0065\u0065\u006e\u0076\u0069\u006c\u006c\u0065\u0020" ); break ; } case "rabid hampster" : { sb.append( "\u0047\u0072\u006f\u0075\u0070\u0020" ); break ; } case "people" : { sb.append( "\u0054\u0068\u0065\u0020" ); break ; } case "orange" : { sb.append( "\u004a\u0061\u0076\u0061\u0020" ); break ; } default : { sb.append( "Awesome!" ); break ; } } } System.out.println(sb.toString()); System.out.println( "Thanks for attending this evening." ); } } |
1 comments :
Good example and String in Switch is more useful.
Post a Comment