DEV Community

Neelakandan R
Neelakandan R

Posted on

switch , while loop

Java Switch Statements

Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

Points to Remember

There can be one or N number of case values for a switch expression.

The case value must be of switch expression type only. The case value must be literal or constant. It doesn't allow variables.

The case values must be unique. In case of duplicate value, it renders compile-time error.

The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.

Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case.

The case value can have a default label which is optional.

In Java, switch statement mainly provides a more detailed alternative that avoids the usage of nested or several if-else statements when associated with an individual variable.

Image description

In Java, the switch statement can also contain a default label. The default label will be executed only in the situation when none of the case labels are matching the expressions value. The declaring of default label is considered optional, but can be useful in the events of unexpected values or inputs.

Syntax

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Enter fullscreen mode Exit fullscreen mode

This is how it works:

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, and will be described later in this chapter

The example below uses the weekday number to calculate the weekday name:

Example:1

public class Main {
  public static void main(String[] args) {
    int day = 4;
    switch (day) {
      case 1:
        System.out.println("Monday");
        break;
      case 2:
        System.out.println("Tuesday");
        break;
      case 3:
        System.out.println("Wednesday");
        break;
      case 4:
        System.out.println("Thursday");
        break;
      case 5:
        System.out.println("Friday");
        break;
      case 6:
        System.out.println("Saturday");
        break;
      case 7:
        System.out.println("Sunday");
        break;
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Outputs:
"Thursday" (day 4)

The break Keyword

When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more testing.

*A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.
*

The default Keyword

The default keyword specifies some code to run if there is no case match:

Example

int day = 4;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
    break;
  case 7:
    System.out.println("Today is Sunday");
    break;
  default:
    System.out.println("Looking forward to the Weekend");
}
Enter fullscreen mode Exit fullscreen mode

Outputs
"Looking forward to the Weekend"

Example : 1

public class SwitchExample {  
    public static void main(String[] args) {  
        //Declaring a variable for switch expression  
        int number=20;  
        //Switch expression  
        switch(number){  
        //Case statements  
        case 10: System.out.println("10");  
        break;  
        case 20: System.out.println("20");  
        break;  
        case 30: System.out.println("30");  
        break;  
        //Default case statement  
        default:System.out.println("Not in 10, 20 or 30");  
        }  
    }  
    }  

Enter fullscreen mode Exit fullscreen mode

Output:

20

Finding Month Example:

//Java Program to demonstrate the example of Switch statement  
    //where we are printing month name for the given number  
    public class SwitchMonthExample {    
    public static void main(String[] args) {    
        //Specifying month number  
        int month=7;    
        String monthString="";  
        //Switch statement  
        switch(month){    
        //case statements within the switch block  
        case 1: monthString="1 - January";  
        break;    
        case 2: monthString="2 - February";  
        break;    
        case 3: monthString="3 - March";  
        break;    
        case 4: monthString="4 - April";  
        break;    
        case 5: monthString="5 - May";  
        break;    
        case 6: monthString="6 - June";  
        break;    
        case 7: monthString="7 - July";  
        break;    
        case 8: monthString="8 - August";  
        break;    
        case 9: monthString="9 - September";  
        break;    
        case 10: monthString="10 - October";  
        break;    
        case 11: monthString="11 - November";  
        break;    
        case 12: monthString="12 - December";  
        break;    
        default:System.out.println("Invalid Month!");    
        }    
        //Printing month of the given number  
        System.out.println(monthString);  
    }    
    }   

Enter fullscreen mode Exit fullscreen mode

Output:

7 - July

Program to check Vowel or Consonant:

If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive.


    public class SwitchVowelExample {    
    public static void main(String[] args) {    
        char ch='O';    
        switch(ch)  
        {  
            case 'a':   
                System.out.println("Vowel");  
                break;  
            case 'e':   
                System.out.println("Vowel");  
                break;  
            case 'i':   
                System.out.println("Vowel");  
                break;  
            case 'o':   
                System.out.println("Vowel");  
                break;  
            case 'u':   
                System.out.println("Vowel");  
                break;  
            case 'A':   
                System.out.println("Vowel");  
                break;  
            case 'E':   
                System.out.println("Vowel");  
                break;  
            case 'I':   
                System.out.println("Vowel");  
                break;  
            case 'O':   
                System.out.println("Vowel");  
                break;  
            case 'U':   
                System.out.println("Vowel");  
                break;  
            default:   
                System.out.println("Consonant");  
        }  
    }    
    }   

Enter fullscreen mode Exit fullscreen mode

Output:

Vowel

Java Switch Statement is fall-through

The Java switch statement is fall-through. It means it executes all statements after the first match if a break statement is not present.

Example:

//Java Switch Example where we are omitting the  
    //break statement  
    public class SwitchExample2 {  
    public static void main(String[] args) {  
        int number=20;  
        //switch expression with int value  
        switch(number){  
        //switch cases without break statements  
        case 10: System.out.println("10");  
        case 20: System.out.println("20");  
        case 30: System.out.println("30");  
        default:System.out.println("Not in 10, 20 or 30");  
        }  
    }  
    }  

Enter fullscreen mode Exit fullscreen mode

Output:

20
30
Not in 10, 20 or 30

Java Switch Statement with String(TBD)

Java allows us to use strings in switch expression since Java SE 7. The case statement should be string literal.

Example:

SwitchStringExample.java

    //Java Program to demonstrate the use of Java Switch  
    //statement with String  
    public class SwitchStringExample {    
    public static void main(String[] args) {    
        //Declaring String variable  
        String levelString="Expert";  
        int level=0;  
        //Using String in Switch expression  
        switch(levelString){    
        //Using String Literal in Switch case  
        case "Beginner": level=1;  
        break;    
        case "Intermediate": level=2;  
        break;    
        case "Expert": level=3;  
        break;    
        default: level=0;  
        break;  
        }    
        System.out.println("Your Level is: "+level);  
    }    
    }   

Enter fullscreen mode Exit fullscreen mode

Output:

Your Level is: 3

Java Nested Switch Statement

We can use switch statement inside other switch statement in Java. It is known as nested switch statement.

Example:

NestedSwitchExample.java

    //Java Program to demonstrate the use of Java Nested Switch  
    public class NestedSwitchExample {    
        public static void main(String args[])  
          {  
          //C - CSE, E - ECE, M - Mechanical  
            char branch = 'C';                 
            int collegeYear = 4;  
            switch( collegeYear )  
            {  
                case 1:  
                    System.out.println("English, Maths, Science");  
                    break;  
                case 2:  
                    switch( branch )   
                    {  
                        case 'C':  
                            System.out.println("Operating System, Java, Data Structure");  
                            break;  
                        case 'E':  
                            System.out.println("Micro processors, Logic switching theory");  
                            break;  
                        case 'M':  
                            System.out.println("Drawing, Manufacturing Machines");  
                            break;  
                    }  
                    break;  
                case 3:  
                    switch( branch )   
                    {  
                        case 'C':  
                            System.out.println("Computer Organization, MultiMedia");  
                            break;  
                        case 'E':  
                            System.out.println("Fundamentals of Logic Design, Microelectronics");  
                            break;  
                        case 'M':  
                            System.out.println("Internal Combustion Engines, Mechanical Vibration");  
                            break;  
                    }  
                    break;  
                case 4:  
                    switch( branch )   
                    {  
                        case 'C':  
                            System.out.println("Data Communication and Networks, MultiMedia");  
                            break;  
                        case 'E':  
                            System.out.println("Embedded System, Image Processing");  
                            break;  
                        case 'M':  
                            System.out.println("Production Technology, Thermal Engineering");  
                            break;  
                    }  
                    break;  
            }  
        }  
    }  
Enter fullscreen mode Exit fullscreen mode

Output:

Data Communication and Networks, MultiMedia

Java Enum in Switch Statement

Java allows us to use enum in switch statement. Java enum is a class that represent the group of constants. (immutable such as final variables). We use the keyword enum and put the constants in curly braces separated by comma.

Example:(TBD)

JavaSwitchEnumExample.java

    //Java Program to demonstrate the use of Enum  
    //in switch statement  
    public class JavaSwitchEnumExample {      
           public enum Day {  Sun, Mon, Tue, Wed, Thu, Fri, Sat  }    
           public static void main(String args[])    
           {    
             Day[] DayNow = Day.values();    
               for (Day Now : DayNow)    
               {    
                    switch (Now)    
                    {    
                        case Sun:    
                            System.out.println("Sunday");    
                            break;    
                        case Mon:    
                            System.out.println("Monday");    
                            break;    
                        case Tue:    
                            System.out.println("Tuesday");    
                            break;         
                        case Wed:    
                            System.out.println("Wednesday");    
                            break;    
                        case Thu:    
                            System.out.println("Thursday");    
                            break;    
                        case Fri:    
                            System.out.println("Friday");    
                            break;    
                        case Sat:    
                            System.out.println("Saturday");    
                            break;    
                    }    
                }    
            }    
    }    

Enter fullscreen mode Exit fullscreen mode

Output:

Sunday
Monday
Twesday
Wednesday
Thursday
Friday
Saturday

Important Points About Java Switch Statement(TBD)

One of the major important features about Java Switch statement is it's fall through behaviour. It means that in case a case label does not contain a break statement, then the execution will be passed on directly to the next case label. A switch statement can also include a default label, which is executed if none of the case labels match the expression's value. The default label is optional but can be useful for handling unexpected or unspecified values.

Switch statements can only match exact values, and they cannot check ranges of values. This means that if you need to check for a range of values, you would need to use multiple case labels or resort to other control flow statements like if-else.

Switch statements can only be used to check for equality between the expression and the case labels. They cannot perform more complex checks, such as checking conditions or using comparison operators.

The expression in a switch statement must evaluate to a primitive data type (int, char, or enum) or to a String (since Java 7). This limitation restricts the types of expressions that can be used with switch statements, making them less flexible in certain situations compared to other control flow statements.

It's worth noting that starting from Java 12, switch statements have been enhanced to support switch expressions, which allow the switch statement to be used as an expression that returns a value. This feature provides more flexibility and can lead to more concise and readable code in certain situations.

Overall, the switch statement in Java is a powerful tool for controlling the flow of a program based on the value of an expression, offering a clear and efficient way to handle multiple branching scenarios.

Switch statements can sometimes lead to code duplication, especially when multiple case blocks perform similar actions. This can make the code harder to maintain and debug.

While switch statements can be used with String objects since Java 7, they cannot be used directly with other object types. This limitation can make switch statements less useful in scenarios where complex objects need to be compared.

Reference:https://www.javatpoint.com/java-switch

Reference:https://www.w3schools.com/java/java_switch.asp

Java While Loop

Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.
Java While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax

while (condition) {
  // code block to be executed
}
Enter fullscreen mode Exit fullscreen mode

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Example

public class Main {
  public static void main(String[] args) {
    int i = 0;
    while (i < 5) {
      System.out.println(i);
      i++;
    }  
  }
}

Enter fullscreen mode Exit fullscreen mode

Output:
0
1
2
3
4

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!

EXAMPLE:

public class Main {
  public static void main(String[] args) {
    int countdown = 3;

    while (countdown > 0) {
      System.out.println(countdown);
      countdown--;
    }

    System.out.println("Happy New Year!!");
  }
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
3
2
1
Happy New Year!!

Example:

public class Main {
  public static void main(String[] args) {
    int dice = 1;

    while (dice <= 6) {
      if (dice < 6) {
        System.out.println("No Yatzy.");
      } else {
        System.out.println("Yatzy!");
      }
      dice = dice + 1;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Output:

No Yatzy.
No Yatzy.
No Yatzy.
No Yatzy.
No Yatzy.
Yatzy!

If the loop passes the values ranging from 1 to 5, it prints "No Yatzy". Whenever it passes the value 6, it prints "Yatzy!".
**
Reference:**
https://www.w3schools.com/java/java_while_loop.asp

Top comments (0)