SlideShare ist ein Scribd-Unternehmen logo
1 von 30
selection statements of Java




                               1
Objective

On completion of this period you would be able to
  know
• Various selection statements available in Java




                                                    2
Recap

• In the previous class we have discussed
  • Various types of operators




                                            3
Selection statements of Java

• Java language supports the following selection
  statements
• If statement
• Switch statement
• Conditional operator statement



                                                   4
The if Statement
               if ( <boolean expression> ) {


                       <then block>
               }                                   Boolean
                                                   Boolean
                                                  Expression
                                                  Expression

        if (         testScore >= 95   ){
Then
 Then          System.out.println("You are a good student");
Block
Block   }




                                                               5
Control Flow of if

   testScore >=
                          true
    testScore >=
   95?
    95?




                   System.out.println
                    System.out.println
  false
                   ("You are aagood student");
                    ("You are good student");




                                                 6
The if-else Statement


if (testScore < 50) {

                                                  This statement is
                                                   This statement is
    System. out. println ("You did not pass");    executed ififthe testScore
                                                   executed the testScore
                                                  is less than 50.
                                                   is less than 50.

} else {

                                                 This statement is
                                                  This statement is
    System. out. println ("You did pass");       executed ififthe testScore
                                                  executed the testScore
                                                 is 50 or higher.
                                                  is 50 or higher.


}


                                                                    7
Syntax for the if-else Statement
              if ( <boolean expression> ) {
                         <then block>
              } else {
                                                    Boolean
                                                     Boolean
                         <else block> }            Expression
                                                   Expression

                if (testScore < 50) {


                    System.out.println("You did not pass");
  Then
   Then
  Block
  Block
                } else {
                    System.out.println("You did pass");
else Block
else Block
                }

                                                                8
Control Flow

            false                             true
                       testScore < 50 ??
                        testScore < 50




                                           System.out.println
                                            System.out.println
System.out.println
 System.out.println                        ("You did not
                                            ("You did not
("You did pass");
 ("You did pass");                         pass");
                                            pass");




                                                                 9
The Nested-if Statement
• The then and else block of an if statement can contain any
  valid statements, including other if statements. An if
  statement containing another if statement is called a
  nested-if statement
  if (testScore >= 50) {
      if (studentAge < 10) {
          System.out.println("You did a great job");
      } else {
          System.out.println("You did pass");
      }
  } else { //test score < 70
      System.out.println("You did not pass");
  }
                                                           10
Control Flow of Nested-if Statement
                                                         true                       inner if
             false    testScore >= 50 ??
                       testScore >= 50



System.out.println
 System.out.println
                                           false         studentAge < 10
                                                          studentAge < 10
                                                                                 true
("You did not
 ("You did not                                           ??
pass");
 pass");

                                                                            System.out.println
                                                                             System.out.println
                                   System.out.println
                                    System.out.println                      ("You did aagreat
                                                                             ("You did great
                                   ("You did pass");
                                    ("You did pass");                             job");
                                                                                   job");




                                                                                            11
Compound Statements
• You have to use braces if the <then> or <else>
  block has multiple statements
   if (testScore < 70)
   {                                               Then Block
                                                   Then Block
       messageBox.show("You did not pass");
       messageBox.show("Try harder next time");
   }
   else
   {                                               Else Block
                                                   Else Block
       messageBox.show("You did pass");
       messageBox.show("Keep up the good work");
   }                                                    12
Style Guide
if ( <boolean expression> ) {
        …
} else {                          Style 1
                                  Style 1
        …
}

    if ( <boolean expression> )
    {
        …                         Style 2
                                  Style 2
    }
    else
    {
        …
    }                                   13
if - else- if
if (score >= 85) {
        System.out.println(”Grade is A");
                                                               Test        Grad
} else {                                                      Score         e
    if (score >= 75) {
            System.out.println(”Grade is B");               85 ≤ score      A
    } else {
                                                            75 ≤ score <    B
        if (score >= 65) {
                                                            85
                System.out.println(”Grade is C");
        } else {                                            65 ≤ score <    C
            if (score >= 50) {                              75
                 System.out.println(”Grade is D");
                                                            50 ≤ score <    D
            } else {
                                                            65
                 System.out.println(”Grade is N");
            }                                                    score <    N
        }                                                   50
    }
}

                                                                                  14
if - else- if
if (score >= 85) {                         Test        Grad
    System.out.println(”Grade is A");     Score         e
} else if (score >= 75) {
                                        85 ≤ score      A
    System.out.println(”Grade is B");
                                        75 ≤ score <    B
} else if (score >= 65) {               85
    System.out.println(”Grade is C");   65 ≤ score <    C
} else if (score >= 50) {               75
    System.out.println(”Grade is D");   50 ≤ score <    D
} else {                                65
    System.out.println(”Grade is N");        score <    N
                                        50
}


                                                              15
Matching else
    if (x < y)
          if (x < z)
             System.out.println("Hello");
    else
          System.out.println("Good bye");

                            really means
if (x < y) {
      if (x < z) {
            System.out.println("Hello");
      } else {
            System.out.println("Good bye");
      }
}                                              16
Matching else
    if (x < y) {
          if (x < z)
             System.out.println("Hello");
      } else {
             System.out.println("Good bye");
      }
                                  means
if (x < y) {
     if (x < z) {
           System.out.println("Hello");
     }
} else {
    System.out.println("Good bye");
                                               17
}
Syntax for the switch Statement
                     switch ( <arithmetic expression> ) {
                                <case label 1> : <case body 1>
                                …
                                <case label n> : <case body n>
                     }
                                                        Arithmetic Expression
                                                        Arithmetic Expression
        switch ( fanSpeed ) {
             case 1:
Case
 Case
Label       System.out.println("That's low");
Label
            break;
             case 2:
            System.out.println("That's medium");                      Case
                                                                      Case
            break;                                                    Body
                                                                      Body
             case 3:
            System.out.println("That's high");
            break;
        }
                                                                                18
The switch Statement
char standing;
System.out.println("(F)reshman, (S)ophmore, (J)unior, s(E)nior : ");
standing = SavitchIn.readLineNonwhiteChar();


switch (standing) {
     case 'F':                                                 This statement
                                                                This statement
                                                               is executed ifif
                                                                is executed
     System.out.println("Go to the Wellness Center");
                                                               the standing is
                                                                the standing is
     break;                                                    equal to 'F'.
                                                                equal to 'F'.
     case 'S':
     System.out.println("Go to the Cox Building");
     break;
     case 'J':
     System.out.println("Go to Ashe");
     break;
     case 'E':                                          This statement
                                                         This statement
                                                        is executed ifif
                                                         is executed
     System.out.println("Work it out yourself");        the standing is
                                                         the standing is
     break;                                             equal to 'E'.
                                                         equal to 'E'.
                                                                                  19
}
switch With break Statements
                                      true
                              N ==
                              N ==
switch ( N ) {                 11??          xx= 10;
                                                = 10;

    case 1: x = 10;
                          false              break;
                                              break;
                 break;               true
                              N ==
                              N ==
    case 2: x = 20;            22??          xx= 20;
                                                = 20;

                 break;
                          false              break;
                                              break;
    case 3: x = 30;                   true
                              N ==
                              N ==
                 break;        33??          xx= 30;
                                                = 30;
}
                          false              break;
                                              break;




                                                        20
The switch Statement with default
         switch ( <arithmetic expression> ) {
                  <case label 1> : <case body 1>
                  …
                  <case label n> : <case body n>
                  default: <default body>
         }
switch ( binaryDigit ) {
    case 0:
     System.out.println("zero");
     break;
    case 1:
     System.out.println("one");
     break;
    default:
     System.out.println("That's not a binary digit");
     break;
                                                        21
}
Switch With No break Statements

                                     true
                             N ==
                             N ==           xx= 10;
switch ( N ) {                11??             = 10;

    case 1: x = 10;      false
    case 2: x = 20;                  true
                             N ==
                             N ==           xx= 20;
    case 3: x = 30;           22??             = 20;

}                        false
                                     true
                             N ==
                             N ==           xx= 30;
                                               = 30;
                              33??

                         false


                                                       22
Summary

• In this class we have discussed about various
  selection statements




                                                  23
Assignment

• Write a Java program to find whether the given
  year is leap or not
• Write a Java program to find the largest of three
  numbers
• Write a Java program illustrating the functioning
  of switch statement


                                                   24
Quiz

1.The only relational operation that can be
   checked in switch

a) less than
b) greater than
c) equality
d) all of the above



                                              25
Quiz

2.Which of the following control statement requires
   break

a)   If
b)   If else
c)   Switch
d)   All of the above



                                                  26
Quiz

3.Default condition is always required in switch
  statements .[ True/ False]




                                                   27
Quiz

3.Default condition is always required in switch
  statements .[ True/ False]




                                                   28
Frequently Asked Questions

• Differentiate between switch and if else
  statements
• List the various selection statements of Java
• Explain the various selection statements




                                                  29
swings
                Struts
                 jdbc
              hibernate
                home
  java previous question papers
OCT/NOV-2012 QUESTION PAPER
      April / May 2012 c-09
  October/ November-2011 c-09
       April/ May 2011 c-09
       April/ May 2011 c-05




      Home                        30

Weitere ähnliche Inhalte

Ähnlich wie 9 cm604.11

Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
PRN USM
 

Ähnlich wie 9 cm604.11 (20)

130706266060138191
130706266060138191130706266060138191
130706266060138191
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Comp102 lec 5.1
Comp102   lec 5.1Comp102   lec 5.1
Comp102 lec 5.1
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
07 flow control
07   flow control07   flow control
07 flow control
 
Core java
Core javaCore java
Core java
 
Java loops
Java loopsJava loops
Java loops
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
02 - Prepcode
02 - Prepcode02 - Prepcode
02 - Prepcode
 
Control Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptxControl Structures, If..else, switch..case.pptx
Control Structures, If..else, switch..case.pptx
 
Comp102 lec 6
Comp102   lec 6Comp102   lec 6
Comp102 lec 6
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
DAY_1.2.pptx
DAY_1.2.pptxDAY_1.2.pptx
DAY_1.2.pptx
 
White Box Testing V0.2
White Box Testing V0.2White Box Testing V0.2
White Box Testing V0.2
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
Be smart when testing your Akka code
Be smart when testing your Akka codeBe smart when testing your Akka code
Be smart when testing your Akka code
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 

Mehr von myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

9 cm604.11

  • 2. Objective On completion of this period you would be able to know • Various selection statements available in Java 2
  • 3. Recap • In the previous class we have discussed • Various types of operators 3
  • 4. Selection statements of Java • Java language supports the following selection statements • If statement • Switch statement • Conditional operator statement 4
  • 5. The if Statement if ( <boolean expression> ) { <then block> } Boolean Boolean Expression Expression if ( testScore >= 95 ){ Then Then System.out.println("You are a good student"); Block Block } 5
  • 6. Control Flow of if testScore >= true testScore >= 95? 95? System.out.println System.out.println false ("You are aagood student"); ("You are good student"); 6
  • 7. The if-else Statement if (testScore < 50) { This statement is This statement is System. out. println ("You did not pass"); executed ififthe testScore executed the testScore is less than 50. is less than 50. } else { This statement is This statement is System. out. println ("You did pass"); executed ififthe testScore executed the testScore is 50 or higher. is 50 or higher. } 7
  • 8. Syntax for the if-else Statement if ( <boolean expression> ) { <then block> } else { Boolean Boolean <else block> } Expression Expression if (testScore < 50) { System.out.println("You did not pass"); Then Then Block Block } else { System.out.println("You did pass"); else Block else Block } 8
  • 9. Control Flow false true testScore < 50 ?? testScore < 50 System.out.println System.out.println System.out.println System.out.println ("You did not ("You did not ("You did pass"); ("You did pass"); pass"); pass"); 9
  • 10. The Nested-if Statement • The then and else block of an if statement can contain any valid statements, including other if statements. An if statement containing another if statement is called a nested-if statement if (testScore >= 50) { if (studentAge < 10) { System.out.println("You did a great job"); } else { System.out.println("You did pass"); } } else { //test score < 70 System.out.println("You did not pass"); } 10
  • 11. Control Flow of Nested-if Statement true inner if false testScore >= 50 ?? testScore >= 50 System.out.println System.out.println false studentAge < 10 studentAge < 10 true ("You did not ("You did not ?? pass"); pass"); System.out.println System.out.println System.out.println System.out.println ("You did aagreat ("You did great ("You did pass"); ("You did pass"); job"); job"); 11
  • 12. Compound Statements • You have to use braces if the <then> or <else> block has multiple statements if (testScore < 70) { Then Block Then Block messageBox.show("You did not pass"); messageBox.show("Try harder next time"); } else { Else Block Else Block messageBox.show("You did pass"); messageBox.show("Keep up the good work"); } 12
  • 13. Style Guide if ( <boolean expression> ) { … } else { Style 1 Style 1 … } if ( <boolean expression> ) { … Style 2 Style 2 } else { … } 13
  • 14. if - else- if if (score >= 85) { System.out.println(”Grade is A"); Test Grad } else { Score e if (score >= 75) { System.out.println(”Grade is B"); 85 ≤ score A } else { 75 ≤ score < B if (score >= 65) { 85 System.out.println(”Grade is C"); } else { 65 ≤ score < C if (score >= 50) { 75 System.out.println(”Grade is D"); 50 ≤ score < D } else { 65 System.out.println(”Grade is N"); } score < N } 50 } } 14
  • 15. if - else- if if (score >= 85) { Test Grad System.out.println(”Grade is A"); Score e } else if (score >= 75) { 85 ≤ score A System.out.println(”Grade is B"); 75 ≤ score < B } else if (score >= 65) { 85 System.out.println(”Grade is C"); 65 ≤ score < C } else if (score >= 50) { 75 System.out.println(”Grade is D"); 50 ≤ score < D } else { 65 System.out.println(”Grade is N"); score < N 50 } 15
  • 16. Matching else if (x < y) if (x < z) System.out.println("Hello"); else System.out.println("Good bye"); really means if (x < y) { if (x < z) { System.out.println("Hello"); } else { System.out.println("Good bye"); } } 16
  • 17. Matching else if (x < y) { if (x < z) System.out.println("Hello"); } else { System.out.println("Good bye"); } means if (x < y) { if (x < z) { System.out.println("Hello"); } } else { System.out.println("Good bye"); 17 }
  • 18. Syntax for the switch Statement switch ( <arithmetic expression> ) { <case label 1> : <case body 1> … <case label n> : <case body n> } Arithmetic Expression Arithmetic Expression switch ( fanSpeed ) { case 1: Case Case Label System.out.println("That's low"); Label break; case 2: System.out.println("That's medium"); Case Case break; Body Body case 3: System.out.println("That's high"); break; } 18
  • 19. The switch Statement char standing; System.out.println("(F)reshman, (S)ophmore, (J)unior, s(E)nior : "); standing = SavitchIn.readLineNonwhiteChar(); switch (standing) { case 'F': This statement This statement is executed ifif is executed System.out.println("Go to the Wellness Center"); the standing is the standing is break; equal to 'F'. equal to 'F'. case 'S': System.out.println("Go to the Cox Building"); break; case 'J': System.out.println("Go to Ashe"); break; case 'E': This statement This statement is executed ifif is executed System.out.println("Work it out yourself"); the standing is the standing is break; equal to 'E'. equal to 'E'. 19 }
  • 20. switch With break Statements true N == N == switch ( N ) { 11?? xx= 10; = 10; case 1: x = 10; false break; break; break; true N == N == case 2: x = 20; 22?? xx= 20; = 20; break; false break; break; case 3: x = 30; true N == N == break; 33?? xx= 30; = 30; } false break; break; 20
  • 21. The switch Statement with default switch ( <arithmetic expression> ) { <case label 1> : <case body 1> … <case label n> : <case body n> default: <default body> } switch ( binaryDigit ) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; default: System.out.println("That's not a binary digit"); break; 21 }
  • 22. Switch With No break Statements true N == N == xx= 10; switch ( N ) { 11?? = 10; case 1: x = 10; false case 2: x = 20; true N == N == xx= 20; case 3: x = 30; 22?? = 20; } false true N == N == xx= 30; = 30; 33?? false 22
  • 23. Summary • In this class we have discussed about various selection statements 23
  • 24. Assignment • Write a Java program to find whether the given year is leap or not • Write a Java program to find the largest of three numbers • Write a Java program illustrating the functioning of switch statement 24
  • 25. Quiz 1.The only relational operation that can be checked in switch a) less than b) greater than c) equality d) all of the above 25
  • 26. Quiz 2.Which of the following control statement requires break a) If b) If else c) Switch d) All of the above 26
  • 27. Quiz 3.Default condition is always required in switch statements .[ True/ False] 27
  • 28. Quiz 3.Default condition is always required in switch statements .[ True/ False] 28
  • 29. Frequently Asked Questions • Differentiate between switch and if else statements • List the various selection statements of Java • Explain the various selection statements 29
  • 30. swings Struts jdbc hibernate home java previous question papers OCT/NOV-2012 QUESTION PAPER April / May 2012 c-09 October/ November-2011 c-09 April/ May 2011 c-09 April/ May 2011 c-05 Home 30

Hinweis der Redaktion

  1. Chapter 6 -
  2. Chapter 6 - Notice that the if–then statement is not necessary, because we can write any if–then statement using if–then–else by including no statement in the else block. For instance, the sample if–then statement can be written as if (testScore &gt;= 95) { messageBox.show(&quot;You are an honor student&quot;); } else { } In this book, we use if-then statements whenever appropriate.
  3. Chapter 6 -
  4. Chapter 6 -
  5. Chapter 6 -
  6. Chapter 6 -
  7. Chapter 6 - It is possible to write if tests in different ways to achieve the same result. For example, the above code can also be expressed as if (testScore &gt;= 70 &amp;&amp; studentAge &lt; 10) { messageBox.show(&quot;You did a great job&quot;); } else { //either testScore &lt; 70 OR studentAge &gt;= 10 if (testScore &gt;= 70) { messageBox.show(&quot;You did pass&quot;); } else { messageBox.show(&quot;You did not pass&quot;); } }
  8. Chapter 6 -
  9. Chapter 6 - Rules for writing the then and else blocks: - Left and right braces are necessary to surround the statements if the then or else block contains multiple statements. - Braces are not necessary if the then or else block contains only one statement. - A semicolon is not necessary after a right brace.
  10. Chapter 6 - In this book, we will use Style 1, mainly because this style is more common among programmers. If you prefer Style 2, then go ahead and use it. Whichever style you choose, be consistent, because consistent look and feel are very important to make your code readable.
  11. Chapter 6 - If we follow the general rule, the above if-else if will be written as below, but the style shown in the slide is the standard notation. if (score &gt;= 90) messageBox.show(&quot;Your grade is A&quot;); else if (score &gt;= 80) messageBox.show(&quot;Your grade is B&quot;); else if (score &gt;= 70) messageBox.show(&quot;Your grade is C&quot;); else if (score &gt;= 60) messageBox.show(&quot;Your grade is D&quot;); else messageBox.show(&quot;Your grade is F&quot;);
  12. Chapter 6 - If we follow the general rule, the above if-else if will be written as below, but the style shown in the slide is the standard notation. if (score &gt;= 90) messageBox.show(&quot;Your grade is A&quot;); else if (score &gt;= 80) messageBox.show(&quot;Your grade is B&quot;); else if (score &gt;= 70) messageBox.show(&quot;Your grade is C&quot;); else if (score &gt;= 60) messageBox.show(&quot;Your grade is D&quot;); else messageBox.show(&quot;Your grade is F&quot;);
  13. Chapter 6 - If you want the else to match with the first if , then you have to write if (x &lt; y) { if (x &lt; z) messageBox.show(&quot;Hello&quot;); } else messageBox.show(&quot;Good bye&quot;);
  14. Chapter 6 - If you want the else to match with the first if , then you have to write if (x &lt; y) { if (x &lt; z) messageBox.show(&quot;Hello&quot;); } else messageBox.show(&quot;Good bye&quot;);
  15. Chapter 6 -
  16. Chapter 6 -
  17. Chapter 6 -
  18. Chapter 6 -
  19. Chapter 6 -