Switch statement

The switch statement is a multiway branch statement. It is a better alternative than a large series of if-else-if statements. Here is the general form of a switch statement:
switch (expression) {
case value1:
   // statement sequence
   break;
case value2:
   // statement sequence
   break;
.
.
.
case valueN:
   // statement sequence
   break;
default:
   // default statement sequence
}

The expression must be of type byteshortint, or char; each of the values specified in the case statements must be of a type compatible with the expression. If no case matches then the default statement is executed.

PROGRAM
public class SwitchDemo {

 public static void main(String[] args) {
  
  int x = 6;
  System.out.println("x = "+x);
  System.out.print("It is ");
  
  switch(x) {
  
   case 1: System.out.println("One");
    break;
   case 2: System.out.println("Two");
    break;
   case 3: System.out.println("Three");
    break;
   case 4: System.out.println("Four");
    break;
   case 5: System.out.println("Five");
    break;
   case 6: System.out.println("Six");
    break;
   case 7: System.out.println("Seven");
    break;
   case 8: System.out.println("Eight");
    break;
   case 9: System.out.println("Nine");
    break;
   case 0: System.out.println("Zero");
    break;
   default: System.out.println("No. not correct");
  }
 }
}
OUTPUT
C:\>javac SwitchDemo.java
C:\>java SwitchDemo
x = 6
It is Six

Comments

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet