Wednesday, 4 November 2020

The switch Statement in JAVA

 

 

The switch  Statement  :-


A switch statement  allows a variable to be tested  for  equality against a list  of values. Each  value is called  a case , and the variable being switched on is checked for  each case.


The syntax of enhanced for loop is :


switch(expression )

{

    case value:

                                 //Statements

                  break;    //optional

     case value:

                                //Statements

                   break;  //optional

  

 // You can have any number of case statements.

   

   default:              //Optional

                              //Statements

 

   }


 

 

 

EXAMPLE :-

public class Test

{

  public  static void main(String args[])

    {

        //char grade = args[0].charAt(0);

         char grade = 'C' ;

          switch(grade)

       {

       case 'A' :

              System.out.println( "Excellent !");

              break;

       case 'B' :

       case 'C' :

               System.out.println("Well done");

                break;

        case 'D' :

                System.out.println("You passed");

        case 'F' :

                System.out.println("Better try  again");

            

              break;


         default :


                  System.out.println("Invalid grade");

                }

             System.out.println("Your grade is "+ grade);


      }

 }



Compile  and run above program using  various command line arguments.This would produce the following result :


    C:\java\bin>java Test

      Well done

       Your grade is a C






No comments:

Post a Comment

Student Marks Calculation app using java

      import javax.swing. *; import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; public class Student { private J...