chapter 4 introduction to control statements (branching statements) section 1 - additional java...

51
Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4 - Extended If Statements Go Go Go Go

Upload: horace-cunningham

Post on 01-Jan-2016

232 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

Chapter 4

Introduction to Control Statements

(Branching Statements)

Section 1 - Additional Java Operators

Section 2 - If Statements

Section 3 - If-Else Statements

Section 4 - Extended If Statements

Go

Go

Go

Go

Page 2: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

Chapter 4 Section 1Additional Java Operators

• Extended Assignment Operators

• Increment & Decrement Operators

• Relational Operators

• Logical Operators

2

Page 3: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.1 Extended Assignment Operators

These are special assignment operators for arithmetic operations and concatenation.

They have the same low precedence as the standard assignment operator =.

Here are the extended assignment operators:

+= Addition and Concatenation

-= Subtraction

*= Multiplication

/= Division

%= Modulus

3

Page 4: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.1 Extended Assignment OperatorsLook closely at the lines of code that use the extended

assignment operators below and see the equivalent lines of code. Look closely at the values stored in the variables x and str after the lines are executed.

int x = 10;

String str = “Java”;

x += 5; // equivalent to x = x + 5; x now holds 15

x -= 3; // equivalent to x = x - 3; x now holds 12

x *= 2; // equivalent to x = x * 2; x now holds 24

x /= 4; // equivalent to x = x / 4; x now holds 6

x %= 5; // equivalent to x = x % 5; x now holds 1

str += “ Rules!”; // equivalent to str = str + “ Rules”; str holds “Java Rules”

4

Page 5: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.1 The Increment & Decrement OperatorsThe Increment operator is ++

– It increases the value of an int or double variable by 1.

The Decrement operator is --– It decreases the value of an int or double variable by 1.

The following code shows you how to use ++ and --

int x = 10;

int y = 20;

double w= 7.8;

double z = 14.3;

x++; // equivalent to x = x + 1; or x += 1; x now holds 11

y--; // equivalent to y = y - 1; or y -= 1; y now holds 19

w++; // equivalent to w = w + 1; or w += 1; w now holds 8.8

z--; // equivalent to z = z - 1; or z -= 1; z now holds 13.3

5

Page 6: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.1 Relational Operators

Do not place a space between the operators that use two symbols … >= <= == or !=

Relational operators are used to form Boolean Expressions for if and loop statements. Here are the six relational operators:

Operator Relationship

== equal to

!= not equal to

< less than

<= less than or equal to

> greater than

>= greater than or equal to

You’ll see how to use these soon.

6

Page 7: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.1 Logical Operators

Do not place a space between the operators that use two symbols … && and | |

Logical operators are used to modify or form compound Boolean Expressions for if and loop statements. There are three logical operators:

Operator Relationship

! Not

&& And

| | Or

You’ll see how to use these soon. 7

Page 8: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.1 Updated Precedence Chart for Operators

8

Operator Symbol Precedence Level Association

Parentheses ( ) 1 ---------

Method Selector . 2 left to right

Unary Minus - 3 ---------

Unary Plus + 3 ---------

Not ! 3 ---------

Construction new 3 right to left

Casting (int)

(double)

3 right to left

Division / 4 left to right

Multiplication * 4 left to right

Mod or Remainder % 4 left to right

Subtraction - 5 left to right

Addition + 5 left to right

Relational Operators == != < <= > >= 6 ---------

And && 8 left to right

Or | | 9 left to right

Assignment = += -= *= /= %= 10 right to left

Page 9: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

Chapter 4 Section 2

If Statements

9

Page 10: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.2 Introduction to If StatementsIn Java you can execute a segment of code if a Boolean condition is

true. So if the Boolean condition is false, then nothing is executed. You do this by using an if statement.

Here is the general form of an if statement:

if (some Boolean expression is true)

{

// execute this code only between the curly braces

}

The code inside the if statement is NOT executed if the boolean condition is false.

Note that curly braces { } encompass all of the statements inside the body of the if statement. There can be one or many.

10

Page 11: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.2 Evaluating Boolean Expressions

int a = 3, b = 7, c = 10, d = -20;

if (a < b) is true

if (a <= b) is true

if (a == b) is false

if (a != b) is true

if (a - b > c + d) is true

if ( a < b < c) invalid Java statement but valid in algebra

if (a == b == c) invalid Java statement

You will be shown how to accomplish the last two statements later.

11

Page 12: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.2 If Statement ExampleConsider the following code:

System.out.print (“Enter an integer: ”);

int num = reader.nextInt();

if (num % 5 == 0) {

System.out.print (num + “is evenly divisible by 5”);}

Note the use of the equals operator == to compare the two values of num % 5 and 0 to see if they are equivalent. If they are equivalent the entire expression evaluates to true, otherwise it evalutes to false and nothing is printed.

12

Page 13: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.2 if Statement Code ExampleHere is code that will calculate a salesperson’s pay. It will double a

salesperson’s commission from 10% to 20% if sales are over

$2,000.00:

double commission = 0.10; // regular commission is 10%

System.out.print(“Enter the person’s sales for the month: ”);

double sales = reader.nextDouble();

if (sales > 2000.00)

commission *= 2;

double pay = sales * commission;

System.out.println(“Your pay is: ” + pay);

Note: if there is only one line of code inside the if statement, then you don’t have to put curly braces around the body of the if, but we indent to show for readability to sho that it is inside the if statement. If we didn’t indent it would still be inside the if statement.

13

Page 14: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.2 if Statement Code ExampleIf a worker is paid $8.50 per hour for all hours up to and including 40 hours per week, but is paid a time and a half wage of $12.75 per hour for any hours over 40 hours per week, then the person’s pay could be calculated using the following:

System.out.print(“Enter the number of hours worked this week: ”);

double hoursWorked = reader.nextDouble();

double pay = hoursWorked * 8.50;

if (hoursWorked > 40)

{

double overTimeHours = hoursWorked - 40;

pay += overTimeHours * 4.25;

}

System.out.println(“The employee’s pay is: ” + pay);

14

Page 15: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.2 The Form of an if StatementEither use of curly braces below works, but the second is preferred for readabiltiy and troubleshooting!

if (condition) { // saves lines by putting { on same line of conditionstatement;statement;

} No semicolon goes here!

if (condition) No semicolon goes here!{ // adds readability by putting curly brace { here

statement; // because braces are indented atstatement; // the same level (preferred)

} // Easier to find curly brace problems!!!

Note: the statements are executed only if the condition is true, otherwise this control statement is skipped and nothing is executed.

15

Page 16: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.2 The Form of an if StatementNo curly braces needed when only one statement is in the branch.

if (condition) statement;

If curly braces aren’t used, then only the first statement following the if (condition) is in the branch, even if the second statement is accidently indented. Remember: compilers ignore spacing and indentation. Programmers use them for readability.

if (condition) statement1;statement2;

statement2 is indented but it is not in the if statement since there are no curly braces. Another example is on the next slide.

16

Page 17: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.2 if Statement Indentation Error

if (grade > 100) System.out.println(“You cannot have a grade over 100.”);System.out println(“Show your parents your grade before continuing.”);

Here the first println statement is executed only when grade is greater than 100. The second println statement is incorrectly indented and will be executed even if the first one is not.

Sometimes programmers get in a hurry and don’t write branching statements correctly.

How might you rewrite the one above?

17

Page 18: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.2 if Statement Indentation ErrorHow might you rewrite the one on the previous slide so it is readable and shows what is intended?

if (grade > 100){

System.out.println(“You cannot have a grade over 100.”);}System.out println(“Show your parents your grade before continuing.”);

or

if (grade > 100) System.out.println(“You cannot have a grade over 100.”);

System.out println(“Show your parents your grade before continuing.”);

Note the blank line after the first System.out.println in the second version.

second version

first version

18

Page 19: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

Chapter 4 Section 3

If-Else Statements

19

Page 20: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 Introduction to If-Else Statements

In Java you can execute one segment of code if a boolean condition is true or you can execute another segment of code if the condition is false by using an if-else statement. An if-else statement looks like this:

if (some Boolean expression is true) {

// execute this code only if the Boolean expression is true}else{

// execute this code only if the Boolean expression is false}

Note the { } that encompass all of the statements inside the if branch and another set of { } encompass all of the statements inside the else branch.

Curly braces always occur in pairs!20

Page 21: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 if-else Statement Code Example

System.out.print(“Enter a celsius temperature: ”);

double celsius = reader.nextDouble();

double fahr;

if ( celsius > -273.16)

{

fahr = 9.0 * 5.0 * celsius + 32.0;

}

else

{

System.out.print(“The fahrenheit temperature ”);

System.out.println(“cannot be calculated.”);

}

21

Page 22: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 if-else Statement Code ExampleHere is code that will calculate a salesperson’s pay. It will double a salesperson’s commission from 10% to 20% if sales are over $2,000.00, but it is written differently from what we saw before:

double commission;

System.out.print(“Enter the person’s sales for the month: ”);

double sales = reader.nextDouble();

if (sales > 2000.00)

{

commission = 0.20; // bonus commission is 20%

}

else

{

commission = 0.10; // regular commission is 10%

}

double pay = sales * commission;

System.out.println(“Your pay is: ” + pay);22

Page 23: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 if-else Statement Code Example

If a worker is paid $8.50 per hour for all hours up to and including 40 hours per week, but is paid a time and a half wage of $12.75 per hour for any hours over 40 hours per week, then the person’s pay could be calculated using the following:

System.out.print(“Enter the number of hours worked this week: ”);

double hoursWorked = reader.nextDouble();

double pay;

if (hoursWorked <= 40)

pay = hoursWorked * 8.50;

else

{

pay = 40 * 8.5 + (hoursWorked - 40) * 12.75;

}

System.out.println(“The employee’s pay is: ” + pay);

23

Page 24: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 Checking Input with if-else Statements if-else statements are commonly used to check user inputs before processing them.

System.out.print("Enter the radius: ");

double radius = reader.nextDouble();

if (radius < 0)

S

y

s

t

e

m

.

o

u

t

.

p

r

i

n

t

l

n

(

"

E

r

r

o

r

:

R

a

d

i

u

s

m

u

s

t

b

e

>

=

0

"

)

;

else

{

d

o

u

b

l

e

a

r

e

a

=

M

a

t

h

.

P

I

*

M

a

t

h

.

p

o

w

(

r

a

d

i

u

s

,

2

)

;

S

y

s

t

e

m

.

o

u

t

.

p

r

i

n

t

l

n

(

"

T

h

e

a

r

e

a

i

s

"

+

a

r

e

a

)

;

}

24

Page 25: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 Comparison of if-else Statement Formats

Either use of curly braces works:

if (condition) {statement;statement;

} else {statement;

statement;

}

less lines

if (condition){

statement;statement;

}else{

statement;statement;

}

greater readability

Here you see the two ways of formatting an if-else statement. Either works.

One places the curly braces on the same lines as the if condition and the else keyword.

The other one doesn’t so that the curly braces can more easily seen as matched pairs.

Note: the statements in the if branch are executed only if the condition is true, otherwise the statements in the else branch are executed.

One of the two branches will always be executed when you have an if-else statement.

25

Page 26: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 Forms of if and if-else Statementsif and if-else statements can have one or more statements in any

branch as seen in the variety below:

if (condition)

statement;

else

statement;

if (condition)

statement;

else {

statement;

………..

statement;

}

if (condition)

statement;

if (condition)

{

statement;

statement;

}

if (condition)

{

statement;

…..

statement;

}

else

statement;

26

Page 27: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 Important Things about if Statements

• It is better to over-use braces than to under-use them. This can help to eliminate logic errors by adding readability.

• The condition of an if statement must be a Boolean expression that evaluates to either true or false.

• A flowchart can be used to illustrate the behavior of if and if-else statements and develop an over all flow-of-control for a programming segment.

27

Page 28: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 if Statement Flow Chart

28

boolean

condition

Statements

true false

Page 29: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 if-else Statement Flow Chart

29

boolean

condition

Statements

true false

Statements

Page 30: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 Simple Boolean Conditions

You have learned that Java allows you to use an if statement of the form:

if (condition){

….}

The condition can be a simple boolean expression or a compound boolean expression.

Here is a simple boolean expression:

if (grade > 90)System.out.println(“Your grade is A”);

30

Page 31: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.3 Compound Boolean ConditionsJava allows you to use an if statement that has a compound boolean expression in the condition. Compound boolean expressions use the logical operators:

&& (referred to as “AND”)

| | (referred to as “OR”)

! (referred to as “NOT”)

Here are examples using each one:

if (grade > 90 && grade <= 100)System.out.println(“Your grade is A”);

if (grade < 0 | | grade > 100)System.out.println(“Grade not possible.”);

if ( ! (grade > 59) ) // this one is a simple not a compoundSystem.out.println(“Your grade is an F”);

31

Page 32: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

Chapter 4 Section 4

Nested If

and

Extended If

Statements

32

Page 33: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Extended if Statement FormExtended if statements have two or more branches. They have the following general form:

if (condition){

… code

}else if (condition){

… code

}else{

… code

}

The else branch is optional and doesn’t have a condition, but if none of the conditions in the other branches are true then the else branch will be executed.

The else if branch has a condition.

Only one of the three branches of code will be executed.

33

Page 34: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Extended if Statement without ElseAn extended if statement need not have an else branch. If it doesn’t, then code will only

be executed if one of the two conditions is true, otherwise nothing is executed.

if (condition)

{

… code

}

else if (condition){

… code

}

34

Page 35: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Multiple Branches of an Extended if if (condition){

… code

}else if (condition){

… code

}else if (condition){

… code

}….. possible other else if branches

else{

… code

}

An extended if statement may

have many branches. No

matter how many branches it

has only one branch of code

will be executed. If it does not

have an ending else branch,

then again it is possible no

code will be executed.

However, if it does have an

ending else branch then if

none of the conditions in the

other branches are true then

the else branch will be

executed.

35

Page 36: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Modifying Three if StatementsConsider the pseudocode for the following simple if statements. Even

though they have compound boolean expressions, the intention of the code is clear when they follow one another in this order. Here all three if conditions are tested but it is possible that some of them may not be executed:

if (the time is after 7pm && you have a book)read the book

if (the time is after 7pm && ! you have a book)watch TV

if ( ! the time is after 7pm)go for a walk

We will convert the above code to an extended if statement.

36

When if statements are written so that the intent is to have only one thing executed, like read a book, watch TV, or go for a walk, then there is a better way to write the code.

Page 37: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Extended if StatementsHere the if statements have been rewritten as an extended if

statement and the code overall is more readable and it is more efficient because once Java finds a true condition, then that branch is executed and all other branches are skipped!

if (the time is after 7pm && you have a book)

read the book

else if (the time is after 7pm && ! you have a book)

watch TV

else if ( ! the time is after 7pm)

go for a walk

Remember ... you don’t have to have a final else to end an extended if statement, but you can if you want something to be executed if none of the boolean conditions of the extended if are true.

37

Page 38: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Extended if Statements

if (the time is after 7pm && you have a book)

read the book

else if (the time is after 7pm && ! you have a book)

watch TV

else if ( ! the time is after 7pm)

go for a walk

In an extended if statement like this one, it is easier to read and

trace the logic and make sure that every possible situation is

covered. Therefore, we are able to avoid logic errors. It is more

difficult in the next nested if statement.

38

Page 39: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Nested if Statement Logic ErrorsThe nested if statement below is equivalent to the previous extended

if, but it is not as easy to read and is more difficult to trace the logic to make sure every possibility is covered. It takes more time to think about it and verify its correctness.

if (the time is after 7pm){

if (you have a book)read the book

elsewatch TV

} else

go for a walk

39

The inner if-else statement is nested inside the first if branch, therefore we call the first if a nested if.

Page 40: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Flow Chart for a Nested If Statement

This flowchart of a nested if statement

helps us verify the code in a visual manner.

Most of the time when we can visualize code

we can verify its correctness.

The flowchart for an extended-if statement would look exactly the same.

40

Page 41: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Evolution of an Extended If Statement

The next three slides will show you how extended if statements are actually nested if statements.

41

Page 42: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Nestedif Statement Example with the { } braces in the elses.

if (testAverage >= 90)

System.out.print(“Grade is A. ”);

else

{

if (testAverage >= 80)

System.out.print(“Grade is B. ”);

else

{

if (testAverage >= 70)

System.out.print(“Grade is C. ”);

else

{

if (testAverage >= 60)

System.out.print(“Grade is D. ”);

else

{

System.out.print(“Grade is F. ”);

}

}

}

}

Note: there is only one java statement inside each if branch so there are no curly braces for those branches.

There is also just one statement in each else branch even though they have { }, but we will remove the curly braces.

(See next slide)

42

Page 43: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Nestedif Statement Example without the { } braces.

if (testAverage >= 90)

System.out.print(“Grade is A. ”);

else

if (testAverage >= 80)

System.out.print(“Grade is B. ”);

else

if (testAverage >= 70)

System.out.print(“Grade is C. ”);

else

if (testAverage >= 60)

System.out.print(“Grade is D. ”);

else

System.out.print(“Grade is F. ”);

Note: java doesn’t care about spacing or indentation so on the next slide we can move the if statements up to the same line as the word else once the curly braces are removed.

(See next slide)

43

Page 44: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Nestedif Statement Example without the { } braces and reformatted to be an extended if statement.

if (testAverage >= 90)

System.out.print(“Grade is A. ”);

else if (testAverage >= 80)

System.out.print(“Grade is B. ”);

else if (testAverage >= 70)

System.out.print(“Grade is C. ”);

else if (testAverage >= 60)

System.out.print(“Grade is D. ”);

else

System.out.print(“Grade is F. ”);

Now we have a nice readable statement that makes sense because it is easy to read.

44

Page 45: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Extended if Statement Order

if (testAverage >= 60)

System.out.print(“Grade is D. ”);

else if (testAverage >= 70)

System.out.print(“Grade is C. ”);

else if (testAverage >= 80)

System.out.print(“Grade is B. ”);

else if (testAverage >= 90)

System.out.print(“Grade is A. ”);

else

System.out.print(“Grade is F. ”);

If we coded the previous extended if with the conditions in reverse order and entered 93 for the testAverage, which branch would be executed?

(see next slide)

45

Page 46: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Extended if Statement Order

if (testAverage >= 60)

System.out.print(“Grade is D. ”);

else if (testAverage >= 70)

System.out.print(“Grade is C. ”);

else if (testAverage >= 80)

System.out.print(“Grade is B. ”);

else if (testAverage >= 90)

System.out.print(“Grade is A. ”);

else

System.out.print(“Grade is F. ”);

If we coded the previous extended if with the conditions in reverse order and entered 93 for the testAverage, what would happen?

The first branch would be executed and the program would display a “D”.

46

Page 47: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Extended if Statementswith compound boolean expressions

However if we change the simple boolean expression listed first to a compound boolean expression then we ensure the code’s accuracy.

if (testAverage >= 60)

System.out.print(“Grade is D. ”);

becomes

if (testAverage >= 60 && testAverage < 70)

System.out.print(“Grade is D. ”);

(see next slide for the expanded example)47

Page 48: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

4.4 Extended if Statementswith compound boolean expressions

Here is a full extended if with compound boolean expressions, where the order of the branches doesn’t matter because of the compound boolean expressions.

if (testAverage >= 90 && testAverage <= 100)

System.out.print(“Grade is A. ”);

else if (testAverage >= 80 && testAverage < 90)

System.out.print(“Grade is B. ”);

else if (testAverage >= 70 && testAverage < 80)

System.out.print(“Grade is C. ”);

else if (testAverage >= 60 && testAverage < 70)

System.out.print(“Grade is D. ”);

else

System.out.print(“Grade is F. ”);48

Page 49: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

Chapter 4 Review• The Math class provides several useful methods, such as pow,

sqrt,random and abs.

• Java’s extended assignment operators are +=, -=, *=, /=, %=

• Java’s has increment ++ and decrement -- operators that modify a double or int variable by 1.

• Java has the logical operators &&, ||, and ! that can be used in forming boolean expressions.

• Java has the relational operators <, <=, >, >=, ==, and != They compare two values and return a Boolean value. They are used to form Boolean expressions in the conditions of control statements.

49

Page 50: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

Chapter 4 Review

• Use an if-else statement rather than two if statements when

the alternative courses of action are mutually exclusive. This makes

your code more efficient when the segment needs to executed

many times.

• The presence or absence of the {} symbols can seriously affect the

logic of a control statement.

• When testing programs that use if or if-else statements, use

test data that forces the program to exercise all logical branches.

50

Page 51: Chapter 4 Introduction to Control Statements (Branching Statements) Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else

Chapter 4 Summary• if and if-else statements are used to make one-way and two-

way decisions.

• Extended if statements have multiple branches that allow for a

straight forward way for processing data when compound boolean

expressions are used in the branches. The use of compound

boolean expressions when possible eliminates the need for a

precise ordering of the branches.

• An extended if statement can have an ending else branch that will

be executed only if all other branch conditions are false. If there is

no ending else branch, then it is possible that none of the code in

the branches will be executed. 51