Thursday, February 12, 2015

Switch

Switch is used if you know the number of options.Please follow the below example


package Example1;

public class SwitchClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String grade="B";
		switch (grade) {
		case "A":
			System.out.println("Excellent");
			break;
		case "b":
		case "B":
			System.out.println("Good");
			break;
		case "C":
			System.out.println("Average");
			break;
		default:
			System.out.println("Better luck next time");
			break;
		}
	}

}


Output:
Good

Please note, It is case sensitive and there is a difference between 'b' and 'B' and you can see that in the example.
Usage of Break ensures it comes out of the loop as soon as the condition is true else it keeps checking all the case block. If no condition matches then it execute the default block. >>>
------------------------------------------------------------------------------------------------------------