Switch case in Java

Switch case in Java

Switch case comes under selection looping structure where the program has to select one option out of several other options. Switch case is an alternative to if else structure. Many a times a program has to check multiple conditions, in such cases if else structure makes program very lengthy and difficult to understand. In such cases switch case plays an important role. It breaks multiple conditions in cases and checks them one by one. Let’s see a switch case program in Java.

Q. Write a program to show the use of switch case in java.

Code-

import java.util.Scanner;
class example
{
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
	System.out.println("Enter a number from 1-10:");
	int n=sc.nextInt();
	switch(n)
	{
		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;
		case 6:System.out.println("Six");
			break;
		case 7:System.out.println("Seven");
			break;
		case 8:System.out.println("Eight");
			break;
		case 9:System.out.println("Nine");
			break;
		case 10:System.out.println("Ten");
			break;
		default:System.out.println("Invalid");
			break;
	}
  }
}

Output-

switch case java output

Explanation-

First the program will accept a number. Then the program will enter the switch case. Here program will check the number with every case. If it matches with any case it will print the statement accordingly. And if it does not match with any case it will print the message enclosed in default statement.

Program parts-

  1. class– Used to declare a class in java.
  2. public– Access modifier which represents it is visible to all.
  3. static– The main method is declared as static, so it doesn’t require to create an object to invoke the main method.
  4. void– Return type of the method.
  5. main– Represents the starting point of the program.
  6. Scanner– Scanner is a class in java. util package used for obtaining the input.
  7. String[] args– Used for command line argument.
  8. System.out.println()– System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. System.out.println is used to print a statement.
  9. System.in is an InputStream.

Conclusion-

So this is the concept of switch case in Java. We hope it was clear to you. If you have any doubts tell us in the comment section. For daily updates and more such content do follow us on Instagram.

Keep programming!

ErrorFreeProgram.

2 COMMENTS

Leave a Reply

Your email address will not be published. Required fields are marked *