Using Switch statements in java

The if statements makes selections based on the single true or false conditions.
If there are multiple cases we can make the use of nested if else statements but this becomes very complicated.  Java provides the switch statements to handle the multiple conditions efficiently. Once a case is matched the statements  starting from the matched cases are executed until the break is applied. The switch expression must always yield a value of char, byte, short or int and should always be enclosed within a parenthesis.
As for example:

switch (status)

{
case 0: System.out.println("example1");
break;
case 1: System.out.println("example2");
break;
case 3; System.out.println("example 3");
break;

}

Let us see an example that assigns a String variable dayName with 7 days of a week, if day is 0, 1, 2, 3, 4, 5, 6 accordingly.


public class DaysOfWeek {
public static void main(String[] args){

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the day number: ");
int dayName = scanner.nextInt();

if (dayName>0 && dayName <= 7){
switch(dayName){
case 7: System.out.println("Sunday");
break;
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
break;
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
}

}
else{
System.out.println("There is no any day in this number");
} }}

Result:

Enter the day number: 
5
Friday

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s