Showing posts with label Switch-Case. Show all posts
Showing posts with label Switch-Case. Show all posts

Monday, 27 June 2011

JDK 7 : String in Switch

A long overdue and seemingly basic feature but better late than never. So now Java has the feature which dotNet had earlier.
public class StringsInSwitch {

public static void main(String[] args) {
for (String a : new String[]{"foo", "bar", "baz"}) {
switch (a) {
case "foo":
System.out.println("received foo!");
break;
case "bar":
System.out.println("received bar!");
break;
case "baz":
System.out.println("received baz!");
break;
}
}
}

}

Thursday, 21 April 2011

Switches in java

Switch (aka case) statements are used to select which statements are to be executed depending on a variable's value matching a label. default is used for the else situation. The selection variable can only be int or char datatype.
switch (selection)
{
case '1':System.out.println("You typed a 1");break;
case '2':System.out.println("You typed a 2");break;
default:System.out.println("Oops!, that was an invalid entry.");
};

Wednesday, 27 October 2010

Switch statement on enums

public enum Shape { RECTANGLE, CIRCLE, LINE }

The switch statement was enhanced to allow a convenient use of enums. Note that the case values don't have to be qualified with the enum class name, which can be determined from the switch control value.
switch (drawing) {
case RECTANGLE: g.drawRect(x, y, width, height);
break;
case CIRCLE : g.drawOval(x, y, width, height);
break;
case LINE : g.drawLine(x, y, x + width, y + height);
break;
}