Switch Statement In Java
Switch Statement :
In Java, switch statement check the value of given variable or statement against a list of case values and when the match is found a statement-block of that case is executed. Switch statement is also called as multiway decision statement.
Syntax
Syntax:
switch(condition)// condition means case value
{
case value-1:statement block1;break;
case value-2:statement block2;break;
case value-3:statement block3;break;
…
default:statement block-default;break;
}
statement a;
The condition is byte, short, character or an integer. value- 1,value-2,value-3,…are constant and is called as labels. Each of these values be matchless or unique with the statement. Statement block1, Statement block2, Statement block3,..are list of statements which contain one statement or more than one statements. Case label is always end with “:” (colon).
Program: write a program for bank account to perform following operations.-Check balance-withdraw amount-deposit amount
For example :
CODE/PROGRAM/EXAMPLE
import java.io.*;
class bankac
{
public static void main(String args[]) throws Exception
{
int bal=20000;
int ch=Integer.parseInt(args[0]);
System.out.println("Menu");
System.out.println("1:check balance");
System.out.println("2:withdraw amount... plz enter choice
and amount");
System.out.println("3:deposit amount... plz enter choice
and amount");
System.out.println("4:exit");
switch(ch)
{
case 1:System.out.println("Balance is:"+bal);
break;
case 2:int w=Integer.parseInt(args[1]);
if(w>bal)
{
System.out.println("Not sufficient balance");
}
bal=bal-w;
System.out.println("Balance is"+bal);
break;
case 3:int d=Integer.parseInt(args[1]);
bal=bal+d;
System.out.println("Balance is"+bal);
break;
default:break;
}
}
}
// Output:
C:\MCA>javac bankac.java
C:\MCA>java bankac 1
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is:20000
C:\MCA>java bankac 2 2000
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is18000
C:\MCA>java bankac 3 2000
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
Balance is22000
C:\MCA>java bankac 4
Menu
1:check balance
2:withdraw amount... plz enter choice and amount
3:deposit amount... plz enter choice and amount
4:exit
C:\MCA>java bankac