Java Programming | Introduction to Switch Statements

Introduction

This is tutorial on switch statements in java. The program is given below that explains how to use switch statements in java. The program is extendable. Go enjoy the program. Lets begin…….

Program for switch statements in java.

//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class SwitchStatements {
	//void main
		public static void main (String[] args)
		{
			//declare int
			int a;

			//Declare input as scanner
			Scanner input = new Scanner(System.in);

			//Take inputs
			 System.out.println("Enter a no. :");
			 a = input.nextInt();

			 //add a switch statement
			 switch(a)
			 {
			 case 1:
				 System.out.println("One");
				 break;
			 case 2:
				 System.out.println("Two");
				 break;
			 case 3:
				 System.out.println("Three");
				 break;
			 case 4:
				 System.out.println("Four");
				 break;
			 case 5:
				 System.out.println("Five");
				 break;
			 default:
				System.out.println("No. Not found");
			 }
		}
}

Output

Enter a no. :
1
One

How does it work

  1. You enter the number.
  2. The conditional statement prints the number in words.

Extending it

The program can be extended. You can use more numbers or alphabets to expand it. Go ahead…..

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter number.
  5. Declare input as Scanner.
  6. Take the inputs and save it in variables.
  7. Add a Switch Statement.
  8. Add system.out.println() function to print the word.

At the end.

You learnt creating the Java program for Switch Statements. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

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