Switch Case Simplified in Java

Switch case in Java
Spread the love

Switch Case in java
Switch Case in java

Switch Case Simplified in Java

Switch case is a multi-switch used often than if-else. The term Switch in java is a conditional statement that activates only if a matching condition found out of the given input. We can use if-else or if ladder instead of the switch. But If else can be optimized using switch statements. The switch removes the nested if-else and keeps the code more user-friendly, crisp and clean. When compared to the high number of iterations the switch is faster as compared to if-else statements. The switch is classified as a selection statement.

A State Machine the power behind Switch ideation

As long as, we are working with integral values, the switch case can eliminate a lot of messy code that would normally require many statements.

A state machine moves through a series of states based on the input it receives. A number of type of computer programming can be modeled as below:

State machine Switch case
State machine Switch case

 

Switch Case Simplified in Java

Selector case is an expression the produces some value. the switch compares the result of the selector case with the selector case value. If a valid match is found the corresponding statement(s) executes.

If no match occurs the default gets executed. In switch, each case ends with a break which causes execution to jump to the end of the select body but the break statement is optional. If it is missing, the code for the following case statements executes until the next break or end of a select case. It is used to multi-way selection implementation.

Even though characters can be used in the switch, but actually down the line, it produces the integral value of a character. Byte or shorts can also be used in Switch. From Java -7 on words, String values can be passed to Switch as well. However, we can not enter real numbers in Switch.

the switch statement takes the value of a variable or expression against a list of case values and when a match is found, a block of statements associated with the case is executed.

Generic Syntax:

switch(selectCase)
{
case selectCase1(constant1) :statement;break;
case selectCase2(constant2) :statement;break; case selectCase3(constant3) :statement;break; ... ... ... default: statement; }

SelectCase– It is the expression that evaluates an integral or String value.
Case -is the multiway switch position marked with case labels that accept the case constants.
default-default is optional and provides a default jump point when none of the value of the expression is listed in the case. I have written in detail in the below section
break-break statement is technically optional that makes the JVM jump to the end of the switch statement.

An Example:

class MySwitchBoard{
public static void main(String args[])
{
int iSwitch=4;
switch(iSwitch)
{
case 0:
System.out.println("Zero");
break;
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;
default:
System.out.println("default");
}
}
} 
Another Example:
switch(e)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println("vowel");
break;
case 'y':
case 'w':
System.out.println("some times vowel");
break;
default:
System.out.println("Consonent");
} 
Another Example:

Take input from User about the month number and using switch statements to find out the month name.

import java.util.Scanner;
public class Switch {
	public static void main(String[] args) {
		System.out.println("Enter your month number");
		Scanner scan=new Scanner(System.in);
		int monthNumber=scan.nextInt();
		switch(monthNumber)
		{
		case 1:
			System.out.println("January");
			break;
		case 2:	
			System.out.println("February");
			break;	
		case 3:	
			System.out.println("March");
			break;
		case 4:	
			System.out.println("April");
			break;
		case 5:	
			System.out.println("May");
			break;
		case 6:	
			System.out.println("June");
			break;	
			//rest of the code
		default:
		    System.out.println("Invalid month");
}
}
}

Importance of break:
the break statement will break the switch statement once the condition is satisfied. So break will come out of the switch block. The control will not flow to the next case statement. It also signals the end of a particular case and causes an exit from the switch statement, referring the control out of the switch of the next statement. If we do not put the break statement (since it is optional) JVM will execute all the statements associated with the next case label. It is legal but not desired. cases can be stacked on top of each other to provide multiple matches for a code. It is essential to put a break otherwise the control will go to the unwanted block of cases and execute.

Importance of default:

Default is an optional case when present it will be executed if the value of the expression does not match with any of the case values. If not present, no action takes place when all matches fail and the control goes out of the switch statements. This will be executed if no condition matches with cases. So the condition of the remaining steps will be checked and finally execute the default statement.
There is no position for default. It can be placed anywhere in the switch block. Bast practice is to put to the end of the switch block.

Switch Case Simplified in Java
Rules for the switch:
  1. There is no limit for switch case
  2. switch takes input in the form of integer, characters, and String(java -8 onward).
  3. for nonintegral, noncharacter or nonstring cases, we can not use switch rather a series of if statements are required.
  4. The select case values are constant expression known as labels
  5. The select cases are unique within a switch statement.
  6. We can club two or more cases together.
  7. Cases may contain zero or n lines
  8. There is no need to put braces for a block of statements.
  9. Case labels end with a colon(:).

Where can we use Switch in real-time?

In menu items. A menu is a list of options. If the user selects one of the options. The JVM responds to each possible choice differently.
Read here for switch case in the enum.

Here is a tentative implementation of the state machine in java

public class StateMachine {
	static int input[]= {1,2,5,6,3,6,4,4,7,6,4,8};
	static int i=0;
	static char state='A';
	public static void state() {
		System.out.println(i+"state"+input[i]);
	}
	public static void main(String[] args)
	{
		try {
		outer:
			while(true) {
				switch(state) {
				case 'A':
					state();
					switch(input[i])
					{
						case 1:
							state = 'B';
							default:
								
					}
					i++;
					continue outer;
				case 'B':
					state();
					switch(input[i])
					{
						case 2:
							state = 'C';
							
						case 3:
							state = 'E';
						case 4:
							state = 'D';
							default:
					}
					i++;
					continue outer;
				case 'C':
					state();
					switch(input[i])
					{
						case 5:
							state = 'E';
							default:
					}
					i++;
					continue outer;
				case 'D':
					state();
					switch(input[i])
					{
						case 7:
							state = 'E';
							break;
						case 8:
							state = 'F';
							break;
							default:
								
					}
					i++;
					continue outer;
				case 'E':
					state();
					switch(input[i])
					{
						case 6:
							state = 'B';
							default:
					}
					i++;
					continue outer;
				case 'F':
					default:
					state();
					continue outer;
              }
			}
     	}
		catch(Exception e) {
			System.out.println("ran out of events");
		}
	}
	
}

The output of the code:
0state1
1state2
2state5
3state6
4state3
5state6
6state4
7state4
8state7
9state6
10state4
11state8
ran out of events

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.


Spread the love
  •  
    1
    Share
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Comment

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

Scroll to Top