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.


					switch(expression) {
  case x:
    // code block
  case y:
    // code block
    //  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.


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


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

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


Share on