Appendix 1. Language Enhancements

1.1. Use String in the switch statement - Source Code

Code:

package c1.s1;

/**
 * @author Mikalai Zaikin
 */
public class StringSwitch {
    public static void main(String... args) {
        String color = "black";
        switch (color) {
            case "white":
                System.out.print(color + " RGB: ffffff");
                break;
            case "black":
                System.out.print(color + " RGB: 000000");
                break;
            default:
                System.out.print(color + " RGB: UNKNOWN");
                break;
        }
    }
}
					

output:

black RGB: 000000
					

Code:

package c1.s1;

/**
 * @author Mikalai Zaikin
 */
public class StringSwitchCase {
    public static void main(String[] args) {
        String color = "BlAcK";
        switch (color) {
            case "white":
                System.out.print(color + " RGB: ffffff");
                break;
            case "black":
                System.out.print(color + " RGB: 000000");
                break;
            default:
                System.out.print(color + " RGB: UNKNOWN");
                break;
        }
    }
}
					

output:

BlAcK RGB: UNKNOWN
					

Code:

package c1.s1;

/**
 * @author Mikalai Zaikin
 */
public class StringSwitchNull {
    public static void main(String[] args) {
        String color = null;
        switch (color) {
            case "white":
                System.out.print(color + " RGB: ffffff");
                break;
            case "black":
                System.out.print(color + " RGB: 000000");
                break;
            default:
                System.out.print(color + " RGB: UNKNOWN");
                break;
        }
    }
}
					

output:

Exception in thread "main" java.lang.NullPointerException
	at c1.s1.StringSwitchNull.main(StringSwitchNull.java:9)
Java Result: 1
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide