Share on Google+Share on Google+

Switch Statement in java 7

This tutorial describes the if statement in java 7. This is one kind of decision making statement.

Switch Statement in java 7

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 :

  • switch keyword contains the expression.
  • case keyword- it is defined in switch block which holds some expression value and a colon. It defines some statements which is executed if it has the switch expression value.
  • break - It is used with each case statements to terminate the current case execution.
  • default -If no case value matches to the switch expression value, the default block executed.

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";
		case 2:
		days = "Tuesday";
		case 3:
		days = "Wednesday";
		case 4:
		days = "Thursday";
		case 5:
		days = "Friday";
		case 6:
		days = "Saturday";
		case 7:
		days = "Sunday";
		days = "Invalid day";
		System.out.println("Day : " + days);

Output :

Day : Saturday



Posted on: December 22, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Switch Statement in java 7  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image