codingstreets
Search
Close this search box.

Get Started: Java Switch

In This Article, You Will Learn about Java Switch.

Java Booleans – Before moving ahead, let’s know a bit about Java Boolean.

Table of Contents

Java Switch

Java Switch is as same as the if… else statement but instead of writing many if… else statements, Switch statement is used to replace the if… else statements and selects one of many code blocks to be executed.

Syntax

				
					switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    //  code to be executed if all cases are not matched;  
}
				
			

Explanation –

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • The break and default keywords are optional

Points to Remember

  • There could either be one, or all N of possible values for an expression of switch.
  • The value for the case must be of the switch expression type only. The value of the case must be either constant or literal. It does not allow variables.
  • The case values have to be distinct. If there is a duplicate value the compiler will report a time-out error.
  • It is essential that the Java switch expression should consist comprised of short, byte int long, string and int.
  • Each case statement can include a break statement that is not required. When the control gets to the statement that breaks it, it will jump to the control following it has reached the expression for the switch. If a break phrase is not found, it will execute the next scenario.
  • The value of the case can be given an initial label, which can be used as an option.

Example: 

				
					int temperature = 55;
switch (temperature) {
  case 20:
    System.out.println("It is light-cold day");
    break;
  case 29:
    System.out.println("It is a normal day");
    break;
case 40:
    System.out.println("It is a hot day");
    break;
case 55:
    System.out.println("It is too much hot day");
    break;
case 65:
    System.out.println("It is inevitable hotness in weather");
    break;
}
				
			

Example:

				
					String vowel = u;
switch (vowel) {
  case a:
    System.out.println("It is vowel a");
    break;
  case e:
    System.out.println("It is vowel e");
    break;
case i:
    System.out.println("It is vowel i");
    break;
Case o:
    System.out.println("It is vowel o");
    break;
Case u:
    System.out.println("It is vowel u");
    break;
}
				
			

If you find anything incorrect in the above-discussed topic and have further questions, please comment below.

Connect on:

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on