Control Flow Statements - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

Control Flow Statements

Description:

... programmers consider it to be good coding style to always include the curly braces. Leaving out curly braces can cause subtle bugs because most Java programmers ... – PowerPoint PPT presentation

Number of Views:362
Avg rating:3.0/5.0
Slides: 34
Provided by: louis51
Category:

less

Transcript and Presenter's Notes

Title: Control Flow Statements


1
Control Flow Statements
  • The first step
  • The first step in learning to use a new
    programming language is usually to learn the
    foundation concepts such as variables, types,
    expressions, flow-of-control, etc.

2
Control Flow Statements
  • Java programs accomplish their tasks by
    manipulating program data using operators and
    making decisions by testing the state of program
    data. When a program makes a decision, it is
    determining, based on the state of the program
    data, whether certain lines of code should be
    executed. For example, a program may examine a
    variable called hasChanged to determine if it
    should execute a block of code that saves data to
    disk. If hasChanged is true, the data saving code
    is executed. If hasChanged is false, the data
    saving code is not executed.

3
Control Flow Statements
  • At a simplistic level, a program executes
    statements sequentially in the order in which
    they appear. It starts with the first line of the
    "main()" method and ends with the last line,
    always moving from top to bottom.
  • Most useful programs are vastly more complex than
    a simple linear sequence. Real programs contain
    numerous code blocks that must be executed only
    if certain conditions are present. Other code
    blocks must be executed repeatedly until certain
    conditions are met.
  • A hypothetical example A program loops through
    an array of employee models and increases the
    value stored in the salary variable by 10 for
    each employee that has a hire date of one year
    ago. (I said it was hypothetical)

4
Control flow statements
  • Control flow statements are the tools programmers
    use to make decisions about which statements to
    execute and to otherwise change the flow of
    execution in a program. The four categories of
    control flow statements available in Java are
    selection, loop, exception, and branch.

5
Control Flow Statements
6
The first step
  • The first step in learning to use a new
    programming language is usually to learn the
    foundation concepts such as variables, types,
    expressions, flow-of-control, etc

7
Flow of Control
  • What is flow of control?
  • Java support several different kinds of
    statements designed to alter or control the
    logical flow of the program, although in some
    cases, the behavior of those statements differs
    between Java and C.
  • The ability to alter the logical flow of the
    program is often referred to as Flow of Control.

8
Statements that support flow of control
  • Statement Type
  • if-else selection
  • switch-case selectionfor
    loop
  • while loop
  • do-while loop
  • try-catch-finally exception handling
  • throw exception handling
  • break miscellaneous
  • continue miscellaneous
  • label miscellaneous
  • return miscellaneous
  • goto reserved by Java but not
    supported

9
Selection and Loop
  • Selection and loop statements require a
    conditional expression that evaluates to true or
    false.
  • If the conditional expression is true, the
    accompanying block of code is executed.
  • If the conditional expression is false, the
    accompanying block of code is bypassed.

10
Selection statements
  • Selection statements will execute the code block
    only once. Loop statements repeatedly execute the
    code block, testing the conditional statement
    each time.
  • Once the conditional statement evaluates to
    false, the loop exits and execution of the
    program continues to the next statement following
    the loop.

11
Exception
  • Exception statements are used to gracefully
    handle unusual events or errors that arise while
    a program is running.
  • For instance, if a program attempts to open a
    file but the file doesn't exist, this will cause
    an I/O error. Exception handling in Java is a two
    step process.

12
Exception
  • First, an exceptional condition is detected
    during program execution by the JVM or
    application code.
  • At this point a new exception object is created
    that describes the situation and is passed up up
    the call stack using the throw statement.
  • . Each method in the call stack now has the
    option to handle it or let it continue to bubble
    up the call stack.

13
Branch
  • Branch statements explicitly redirect the flow of
    program execution. The most infamous branch
    statement in the history of computing is goto.
  • In Java, goto is an unimplemented keyword, so it
    cannot be used in Java programs.
  • In other languages, goto is used to redirect
    program execution to another line of code in the
    program by specifying a line number or other type
    of label.

14
Branch
  • In Java, break, continue, and label fill the
    role of goto, but without many of goto's
    negatives. return is a branching statement that
    redirects execution out of the current method and
    back to the calling method.
  • It also returns a value to the calling method.
    This value is either a primitive, object, or
    void. void is used to return execution without
    returning a value.
  • Also, whatever the return value is, its type must
    match the return type listed in the method
    declaration.

15
Statements' general form
  • statement_keyword
  • (conditional_expression)
  • statements_to_execute

16
Three parts to the general form
  • Notice from previous slide
  • The statement_keyword is the Java language
    keyword that defines what type of control is
    being exerted on the statements_to_execute code
    block.
  • The conditional_expression defines the
    conditions that must be present for
    statements_to_execute to be executed.

17
statements' general form
  • Notice statements_to_execute is wrapped in curly
    braces
  • If statements_to_execute consists of a single
    statement only, the curly braces are optional.
  • Most Java programmers consider it to be good
    coding style to always include the curly braces.
  • Leaving out curly braces can cause subtle bugs
    because most Java programmers expect the curly
    braces out of habit.

18
Examples
  • Here are some examples of control statements. We
    will cover all of these and more in the future.
  • //Example 1
  • If (conditional_expression)
  • statements_to_execute

19
Examples
  • //Example 2
  • If (conditional_expression)
  • statements_to_execute
  • else
  • statements_to_execute

20
Example Cont
  • //Example 3
  • while(conditional_expression)
  • statements_to_execute
  • //Example 4
  • for(int i 0 conditional_expression i)
  • statements_to_execute

21
Operators Revisited
  • As we saw in Java Control Flow Statements ,
    making decisions in Java is accomplished by
    evaluating the state of program data using
    conditional operators such as , lt, and gt.
  • if statements use the boolean value returned from
    these conditional expressions to determine
    whether the accompanying block of code should be
    executed.
  • If the conditional expression returns true, the
    code block is executed. Otherwise, the code block
    is skipped.

22
The if statement
  • if(conditional_expression)
  • statements_to_execute
  • This general form shows a simple if structure.

23
If statement Cont
  • If the conditional_expression is true then
    statements_to_execute will be executed.
  • The statements_to_execute are wrapped in curly
    braces .
  • If statements_to_execute consists of a single
    statement only, the curly braces are optional.
  • Java programmers consider it to be good coding
    style to always include the curly braces.

24
Lets look at some examples of if
  • //Example 1
  • if(a b)
  • c
  • In example 1, the if tests the equality of a and
    b. If a and b are equal, c is incremented by 1.
  • //Example 2
  • if((x lt y) (y lt z))
  • System.out.println("Of course\n")
    System.out.println("x is less than or equal to
    z")

25
More Examples
  • Example 2 evaluates a compound conditional
    expression.
  • First it tests whether x is less than or equal
    to y. If this is true, then it tests if y is less
    than or equal to z. If that is also true, then it
    prints the two lines of output.
  • //Example 3
  • if(true)
  • System.out.println("This line always
    executes")
  • In example 3, instead of passing the if statement
    a conditional expression that returns a boolean
    value, we pass it the literal boolean value
    "true". The code block in this example will
    always be executed because true always evaluates
    to true.

26
Example 4
  • //Example 4
  • if(!(employee.isManager()))
  • System.out.println("Employee is not a
    manager.")
  • Example 4 introduces the not operator !. !
    toggles a boolean value. In this example, if
    employee.isManager() returns true, the ! operator
    will toggle it to false and the if statement will
    not execute the code block. If employee.isManager(
    ) returns false, the ! operator will toggle it to
    true and the code block will execute

27
if-else
  • What if you want to execute one block of code
    when an expression evaluates to true but execute
    a different block of code when the same
    expression evaluates to false?
  • The if statement alone is not enough because it
    only controls a single block of code.
  • There are two ways to accomplish this.
  • The first way is to use two if statements with
    mutually exclusive conditional expressions.
  • The second way is to use an if-else structure.
    else is always used in conjunction with, and
    following, an if statement. else is the Java
    keyword designed for those situations where you
    must run exactly one of two code blocks.

28
Lets look at some examples
  • //Example 1
  • if(a b)
  • c
  • If(a ! b)
  • c--

29
Example Cont
  • //Example 2
  • if(a b)
  • c
  • else
  • c--

30
Explanations
  • Example 1 uses two mutually exclusive if
    statements to simulate an if-else construct. In
    this example only one of the two if statements
    will be executed. This is less efficient that
    using an if-else to do the same thing.
  • Example 2 is the if-else version of the previous
    example . You can see the if-else requires less
    code than two ifs and requires one less operation
    be performed. (The a ! b is never explicitly
    tested.)

31
Lets look at some examples of if-else-if
  • //Example 1
  • if(color BLUE))
  • System.out.println("The color is blue.")
  • else if (color GREEN)
  • System.out.println("The color is green.")

32
if-else-if
  • //Example 2
  • if(employee.isManager())
  • System.out.println("Is a Manager")
  • else if
  • (employee.isVicePresident())
  • System.out.println("Is a Vice-President")
  • else
  • System.out.println("Is a Worker")

33
Explanations
  • Example 1 shows a simple if-else-if.
  • In this case if the color equals BLUE or GREEN,
    the respective code block is executed.
  • If color equals any other value none of the code
    blocks will be executed.
  • Example 2 uses the if-else-if structure with an
    ending else.
  • In this example two different conditional
    expressions are tested and if neither is true,
    then the else statement's code block is executed
Write a Comment
User Comments (0)
About PowerShow.com