Presentation is loading. Please wait.

Presentation is loading. Please wait.

The if StatementtMyn1 The if Statement The basic if statement allows your program to execute a single statement, or a block of statements enclosed between.

Similar presentations


Presentation on theme: "The if StatementtMyn1 The if Statement The basic if statement allows your program to execute a single statement, or a block of statements enclosed between."— Presentation transcript:

1 The if StatementtMyn1 The if Statement The basic if statement allows your program to execute a single statement, or a block of statements enclosed between braces, if a given condition is true. This is illustrated in the Figure 1.

2 The if StatementtMyn2 condition is true? yes no Statement or Block of Statements Next Statement if(condition) statement; next statement; or if(condition) { statement; … } next statement; Figure 1. The statement or block of statements that follows the if is only executed if condition is true.

3 The if StatementtMyn3 A simple example of an if statement to test the value of a variable called letter: if(letter==‘A’) System.out.println(“The first capital!“); System.out.println(“This is not part of the if structure!!“); The condition to be tested appears ALWAYS in parentheses!!

4 The if StatementtMyn4 package ifstatement; public class Main { public static void main(String[] args) throws java.io.IOException { char ch, answer='K'; System.out.println("I am thinking of a letter between A and Z."); System.out.print("Can you guess it: "); ch=(char)System.in.read(); if(ch==answer) System.out.println("***RIGHT***"); }

5 The if StatementtMyn5 run: I am thinking of a letter between A and Z. Can you guess it: K ***RIGHT*** BUILD SUCCESSFUL (total time: 8 seconds)

6 The if StatementtMyn6 The statement that is to be executed when the condition in an if statement is true can itself be an if statement. This arrangement is called a nested if. The condition of the inner if is only tested if the condition for the outer if is true. An if that is nested inside another can also contain a nested if.

7 The if StatementtMyn7 if(letter>=‘A’) { if(letter<=‘Z’) { System.out.println(“You entered an upper case letter”); … } If this is NOT true, we will never visit here!!


Download ppt "The if StatementtMyn1 The if Statement The basic if statement allows your program to execute a single statement, or a block of statements enclosed between."

Similar presentations


Ads by Google