This tutorial describes the if statement in java 7. This is one kind of decision making statement.
This tutorial describes the if statement in java 7. This is one kind of decision making statement.This tutorial describes the if statement in java 7. This is one kind of decision making statement.
Switch Statements :
The switch statement is used when you want to test many statements based on
some expression. This expression may be any int value, char value or enum value.
The switch block contains many cases according to requirement .It provides
multiple selections with many alternatives.
Basically it has following parts :
Example :
In this example we are using switch -case statement to print the day of week. If day value is 1 then case 1 will execute its statement that is it will assign Sunday to String variable 'days' and use break to jump out the switch block. In the same way it works for day value 2,3..up to 7 to assign days value Monday, Tuesday...up to Saturday. We have written default at the last of all case statement which will execute when day value will not match to any cases. Finally the print statement prints the value of executed case. Here we have given day =6 so the case 6 will execute its statement and it will print Saturday.
package decisionMaking; class SwitchStatement{ public static void main(String[] args){ int day = 6; String days; switch (day) { case 1: days = "Monday"; break; case 2: days = "Tuesday"; break; case 3: days = "Wednesday"; break; case 4: days = "Thursday"; break; case 5: days = "Friday"; break; case 6: days = "Saturday"; break; case 7: days = "Sunday"; break; default: days = "Invalid day"; break; } System.out.println("Day : " + days); } }
Output :
Day : Saturday
Ads