Credits

Saturday, February 21, 2009

Java's Conditional Statement: Switch

Apart from the IF statements, Java uses Switch for a more flexible validation of filter condition.
Check the sample program below:



[+/-] show/hide



class Sampleswitch{
public static void main(String args[])
throws java.io.IOException
{ int a=20,b=4,sum,diff,product,quo;

char ch;

System.out.println("[A]ddition");
System.out.println("[S]ubtraction");
System.out.println("[M]ultiplication");
System.out.println("[D]ivision");
System.out.println("Enter letter of option");
ch=(char)System.in.read(); //to read from keyboard
switch(ch){
case 'A':
case 'a':
sum=a+b;
System.out.println("SUm is "+sum);break;
case 'S':
diff=a-b;
System.out.println("Difference is "+diff);break;
case 'M':
product=a*b;
System.out.println("Product is "+product);break;
case 'D':
//quo=a/b;
System.out.println("Quotient is "+a/b);break;

}

}
}

AddThis