Code For switch Statement

Code For switch Statement


Posted in : Core Java Posted on : October 7, 2010 at 5:14 PM Comments : [ 0 ]

In this example, We will discuss about switch statement used for decision making.

Code For switch Statement

In this example, We will discuss about switch statement used for decision making. Switch is the control statement in java which also turns the normal flow control of the program as per conditions. It works same as If-Else construct. This is the difference between Switch and If-Else construct that switch is used for reduce the if statements. If the multiple choices are available then we generally use the If-Else construct otherwise Switch is easier than the If-Else construct. Switch checks your choice and jump on that case label if the case exists otherwise control is sent to the default label.

In the given example user enters the number between 1 to 6 and get some statement. if the number is greater than 6 then a message is printed to run again the program.

Example: SwitchExample.java

package com.devmanuals2;

import java.io.*;

public class SwitchExample {

	public static void main(String[] args) throws IOException {
		System.out.println("Enter any no from 1 to 6");
		BufferedReader buffread = new BufferedReader(new InputStreamReader(
				System.in));
		String str = buffread.readLine();
		Integer ch = Integer.parseInt(str);
		if (ch < 7) {
			switch (ch) {
			case 1:
				System.out.println("You are a smart person");
				break;
			case 2:
				System.out.println("You are a clever person");
				break;
			case 3:
				System.out.println("You are a follower person");
				break;
			case 4:
				System.out.println("You are a unsatisfied person");
				break;
			case 5:
				System.out.println("You are a lazy person");
				break;
			case 6:
				System.out.println("You are a disappointed person");
				break;
			}
		} else {
			System.out.println("Run again and Enter right number");
		}

	}

}

Output:

Enter any no from 1 to 6

7

Run again and Enter right number

Download The Example.

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics