Results 1 to 4 of 4

Thread: Switch construct in java

  1. #1
    mehdi Guest

    Switch construct in java

    Hi,

    I am new to Java programming & I am just converting some of my C++ programs in Java. So It would be helpful for me if someone please let me know how the switch control Statements works in Java with an example if possible.

    Thanks in advance.

  2. #2
    Join Date
    Apr 2008
    Posts
    51

    Re: Switch construct in java

    The switch Statement

    Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. The following program, SwitchDemo, declares an int named month whose value represents a month out of the year. The program displays the name of the month, based on the value of month, using the switch statement.

    Code:
    class SwitchDemo {
        public static void main(String[] args) {
    
            int month = 8;
            switch (month) {
                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;
                case 7:  System.out.println("July"); break;
                case 8:  System.out.println("August"); break;
                case 9:  System.out.println("September"); break;
                case 10: System.out.println("October"); break;
                case 11: System.out.println("November"); break;
                case 12: System.out.println("December"); break;
                default: System.out.println("Invalid month.");break;
            }
        }
    }
    In this case, "August" is printed to standard output.

    The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case.

    Of course, you could also implement the same thing with if-then-else statements:

    Code:
    int month = 8;
    if (month == 1) {
        System.out.println("January");
    } else if (month == 2) {
        System.out.println("February");
    }
    . . . // and so on
    Deciding whether to use if-then-else statements or a switch statement is sometimes a judgment call. You can decide which one to use based on readability and other factors. An if-then-else statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or enumerated value.

  3. #3
    Join Date
    May 2008
    Posts
    21

    Re: Switch construct in java

    switch Statement - Overview

    Purpose of switch: select one of many possible statements to execute

    The if statement allows you to select one of two sections of code to execute based on a Boolean value (only two possible values). The switch statement allows you to choose from many statements based on an integer (including char) or enum value.

    Syntax example

    Code:
    switch (expr) {
      case c1:
            statements // do these if expr == c1
            break;
      case c2: 
            statements // do these if expr == c2
            break;
      case c2:
      case c3:
      case c4:         //  Cases can simply fall thru.
            statements // do these if expr ==  any of c's
            break;
      . . .
      default:
            statements // do these if expr != any above
    }

    Switch keywords

    switch
    The switch keyword is followed by a parenthesized integer expression, which is followed by the cases, all enclosed in braces.. The switch statement executes the case corresponding to the value of the expression. Normally the code in a case clause ends with a break statement, which exits the switch statement and continues with the statement following the switch. If there is no corresponding case value, the default clause is executed. If no case matched and there is no default clause, execution continues after the end of the switch statement.
    case
    The case keyword is followed by an integer constant and a colon. This begins the statements that are executed when the switch expression has that case value.
    default
    If no case value matches the switch expression value, execution continues at the default clause. This is the equivalent of the "else" for the switch statement. It is written after the last case be convention, and typically isn't followed by break because execution just continues out the bottom of switch if this is the last clause.
    break
    The break statement causes execution to exit to the statement after the end of the switch. If there is no break, execution flows through into the next case. Flowing directly into the next case is almost always an error.

  4. #4
    Join Date
    May 2008
    Posts
    44

    Re: Switch construct in java

    Java - The switch construct in Java

    Switch is the control statement in java which also turns the normal flow control of the program as per conditions. It works same as If-Else construct. This is the difference between Switch and If-Else construct that switch is used for reduce the if statements. If the multiple choices are available then we generally use the If-Else construct otherwise Switch is easier than the If-Else construct. Switch checks your choice and jump on that case label if the case exists otherwise control is sent to the default label.

    Code:
    import java.io.*;
    
    public class Switch{
      public static void main(String args[]) throws Exception{
          int ch;
        System.out.println("Enter 1 for Sunday.");
        System.out.println("Enter 2 for Monday.");
        System.out.println("Enter 3 for Tuesday.");
        System.out.println("Enter 4 for Wednesday.");
        System.out.println("Enter 5 for Thrusday.");
        System.out.println("Enter 6 for Friday.");
        System.out.println("Enter 7 for Saturday.");
        System.out.print("your choice is : ");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        try{
          ch=Integer.parseInt(in.readLine());
          switch(ch){        
            case 1:  System.out.println("Sunday");
                break;
            case 2:  System.out.println("Monday");
                break;
            case 3:  System.out.println("Tuesday");
                break;
            case 4:  System.out.println("Wednesday");
                break;
            case 5:  System.out.println("Thrusday");
                break;
            case 6:  System.out.println("Friday");
                break;
            case 7:  System.out.println("Saturday");
                break;
            default: System.out.println("Invalid entry!");
                 break;
          }
        }
        catch(NumberFormatException ex){
          System.out.println(ex.getMessage() + " is not a numeric value.");
          System.exit(0);
        }
      }
    }

Similar Threads

  1. Switch in Java
    By cloud101 in forum Software Development
    Replies: 3
    Last Post: 19-01-2012, 07:04 PM
  2. How to use switch statement in java
    By Raju Chacha in forum Software Development
    Replies: 2
    Last Post: 19-01-2012, 06:40 PM
  3. Tips to switch between the Microsoft VM and Sun Java
    By Oren10 in forum Tips & Tweaks
    Replies: 1
    Last Post: 27-05-2011, 05:48 AM
  4. Help!! Java 5, boxing and auto switch.
    By Dewei in forum Software Development
    Replies: 5
    Last Post: 22-09-2010, 10:15 PM
  5. If / else / else if / switch box in Java
    By Samir_1 in forum Guides & Tutorials
    Replies: 2
    Last Post: 11-07-2009, 01:49 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,751,691,570.61520 seconds with 16 queries