SlideShare a Scribd company logo
1 of 50
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
C HA PT E R 4
Decision
Structures
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics
The if Statement
The if-else Statement
The PayRoll class
Nested if Statements
The if-else-if Statement
Logical Operators
Comparing String Objects
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Topics (cont’d)
More about Variable Declaration and
Scope
The Conditional Operator
The switch Statement
The DecimalFormat Class
The SalesCommission Class
Generating Random Numbers with the
Random Class
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The if Statement
The if statement decides whether a
section of code executes or not.
The if statement uses a boolean to
decide whether the next statement or
block of statements executes.
if (boolean expression is true)
execute next statement.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Flowcharts
• If statements can be modeled as a flow
chart.
Wear a coat.
YesIs it cold
outside?
if (coldOutside)
wearCoat();
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Flowcharts (cont’d)
• A block if statement may be modeled
as:
Wear a coat.
YesIs it cold
outside?
Wear a hat.
Wear gloves.
if (coldOutside)
{
wearCoat();
wearHat();
wearGloves();
}
Note the use of curly
braces to block several
statements together.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Relational Operators
• In most cases, the boolean expression, used
by the if statement, uses relational
operators.
Relational Operator Meaning
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
== is equal to
!= is not equal to
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Boolean Expressions
• A boolean expression is any variable or
calculation that results in a true or false
condition.
Expression Meaning
x > y Is x greater than y?
x < y Is x less than y?
x >= y Is x greater than or equal to y?
x <= y Is x less than or equal to y.
x == y Is x equal to y?
x != y Is x not equal to y?
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if Statements and Boolean
Expressions
if (x > y)
System.out.println("X is greater than Y");
if(x == y)
System.out.println("X is equal to Y");
if(x != y)
{
System.out.println("X is not equal to Y");
x = y;
System.out.println("However, now it is.");
}
Example: AverageScore.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Programming Style and if
Statements
• An if statement can span more than one line;
however, it is still one statement.
if (average > 95)
grade = ′A′;
is functionally equivalent to
if(average > 95) grade = ′A′;
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Programming Style and if
Statements (cont’d)
• Rules of thumb:
– The conditionally executed statement should be
on the line after the if condition.
– The conditionally executed statement should be
indented one level from the if condition.
– If an if statement does not have the block
curly braces, it is ended by the first semicolon
encountered after the if condition.
if (expression)
statement;
No semicolon here.
Semicolon ends statement here.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Having Multiple Conditionally-
Executed Statements
Conditionally executed statements can be grouped
into a block by using curly braces {} to enclose them.
If curly braces are used to group conditionally
executed statements, the if statement is ended by the
closing curly brace.
if (expression)
{
statement1;
statement2;
} Curly brace ends the statement.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Having Multiple Conditionally-
Executed Statements (cont’d)
Remember that when the curly braces are not
used, then only the next statement after the
if condition will be executed conditionally.
if (expression)
statement1;
statement2;
statement3;
Only this statement is conditionally executed.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Flags
A flag is a boolean variable that monitors some
condition in a program.
When a condition is true, the flag is set to true.
The flag can be tested to see if the condition has
changed.
if (average > 95)
highScore = true;
Later, this condition can be tested:
if (highScore)
System.out.println("That′s a high score!");
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Comparing Characters
Characters can be tested using the relational
operators.
Characters are stored in the computer using the
Unicode character format.
Unicode is stored as a sixteen (16) bit number.
Characters are ordinal, meaning they have an order
in the Unicode character set.
Since characters are ordinal, they can be compared
to each other.
char c = ′A′;
if(c < ′Z′)
System.out.println("A is less than Z");
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if-else Statements
The if-else statement adds the ability to
conditionally execute code when the if
condition is false.
if (expression)
statementOrBlockIfTrue;
else
statementOrBlockIfFalse;
See example: Division.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Payroll Class
Payroll
- hoursWorked : double
- payRate : double
+ Payroll()
+ setHoursWorked(hours : double) : void
+ setPayRate(rate : double): void
+ getHoursWorked() : double
+ getPayRate() : double
+ getGrossPay() : double
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if-else Statement
Flowcharts
Wear a coat.
YesIs it cold
outside?
Wear shorts.
No
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Nested if Statements
If an if statement appears inside
another if statement (single or block)
it is called a nested if statement.
The nested if is executed only if the
outer if statement results in a true
condition.
See example: LoanQualifier.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Nested if Statement
Flowcharts
Wear a jacket.
YesIs it cold
outside?
Wear shorts.
Is it
snowing?
Wear a parka.
No
No Yes
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if-else Matching
Curly brace use is not required if there
is only one statement to be
conditionally executed.
However, sometimes curly braces can
help make the program more readable.
Additionally, proper indentation makes
it much easier to match up else
statements with their corresponding if
statement.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if-else Matching
if (employed == ′y′)
{
if (recentGrad == ′y′)
{
System.out.println("You qualify for the " +
"special interest rate.");
}
else
{
System.out.println("You must be a recent " +
"college graduate to qualify.");
}
}
else
{
System.out.println("You must be employed to qualify.");
}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if-else-if Statements
if-else-if statements can become
very complex.
Imagine the following decision set.
if it is very cold, wear a heavy coat,
else, if it is chilly, wear a light jacket,
else, if it is windy wear a windbreaker,
else, if it is hot, wear no jacket.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if-else-if Statements
if (expression)
statement or block
else if (expression)
statement or block
// Put as many else ifs as needed here
else
statement or block
Care must be used since else statements match up with the
immediately preceding unmatched if statement.
See example:
TestGrade.java, TestResults.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
if-else-if Flowchart
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Logical Operators
Java provides two binary logical
operators (&& and ||) that are used to
combine boolean expressions.
Java also provides one unary (!) logical
operator to reverse the truth of a
boolean expression.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Logical Operators
Operator Meaning Effect
&& AND
Connects two boolean expressions into one. Both
expressions must be true for the overall expression to
be true.
|| OR
Connects two boolean expressions into one. One or
both expressions must be true for the overall
expression to be true. It is only necessary for one to be
true, and it does not matter which one.
! NOT
The ! operator reverses the truth of a boolean
expression. If it is applied to an expression that is
true, the operator returns false. If it is applied to an
expression that is false, the operator returns true.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The && Operator
The logical AND operator (&&) takes two operands
that must both be boolean expressions.
The resulting combined expression is true if (and
only if) both operands are true.
See example: LogicalAnd.java
Expression 1 Expression 2 Expression1 && Expression2
true false false
false true false
false false false
true true true
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The || Operator
The logical OR operator (||) takes two operands that
must both be boolean expressions.
The resulting combined expression is false if (and
only if) both operands are false.
Example: LogicalOr.java
Expression 1 Expression 2 Expression1 || Expression2
true false true
false true true
false false false
true true true
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The ! Operator
The ! operator performs a logical NOT operation.
If an expression is true, !expression will be false.
if (!(temperature > 100))
System.out.println("Below the maximum temperature.");
If temperature > 100 evaluates to false, then the
output statement will be run.
Expression 1 !Expression1
true false
false true
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Short Circuiting
Logical AND and logical OR operations
perform short-circuit evaluation of
expressions.
Logical AND will evaluate to false as soon
as it sees that one of its operands is a
false expression.
Logical OR will evaluate to true as soon as
it sees that one of its operands is a true
expression.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Order of Precedence
The ! operator has a higher order of
precedence than the && and ||
operators.
The && and || operators have a lower
precedence than relational operators
like < and >.
Parenthesis can be used to force the
precedence to be changed.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Order of Precedence
Order of
Precedence
Operators Description
1 (unary negation) ! Unary negation, logical NOT
2 * / % Multiplication, Division, Modulus
3 + - Addition, Subtraction
4 < > <= >= Less-than, Greater-than, Less-than or
equal to, Greater-than or equal to
5 == != Is equal to, Is not equal to
6 && Logical AND
7 || Logical NOT
8
= += -=
*= /= %=
Assignment and combined assignment
operators.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Comparing String Objects
In most cases, you cannot use the relational
operators to compare two String objects.
Reference variables contain the address of
the object they represent.
Unless the references point to the same
object, the relational operators will not return
true.
See example: GoodStringCompare.java
See example: StringCompareTo.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Ignoring Case in String
Comparisons
In the String class the equals and
compareTo methods are case
sensitive.
In order to compare two String
objects that might have different case,
use:
equalsIgnoreCase
compareToIgnoreCase
See example: SecretWord.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Variable Scope
In Java, a local variable does not have to be
declared at the beginning of the method.
The scope of a local variable begins at the
point it is declared and terminates at the end
of the method.
When a program enters a section of code
where a variable has scope, that variable has
come into scope, which means the variable
is visible to the program.
See example: VariableScope.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Conditional Operator
The conditional operator is a ternary (three
operand) operator.
You can use the conditional operator to write
a simple statement that works like an if-
else statement.
The format of the operators is:
expression1 ? expression2 : expression3
The conditional operator can also return a
value.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Conditional Operator
The conditional operator can be used
as a shortened if-else statement:
x > y ? z = 10 : z = 5;
This line is functionally equivalent to:
if(x > y)
z = 10;
else
z = 5;
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Conditional Operator
Many times the conditional operator is
used to supply a value.
number = x > y ? 10 : 5;
This is functionally equivalent to:
if(x > y)
number = 10;
else
number = 5;
See example: ConsultantCharges.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The switch Statement
The if-else statement allows you to make
true / false branches.
The switch statement allows you to use an
ordinal value to determine how a program
will branch.
The switch statement can evaluate a char,
byte, short, int, or string value and make
decisions based on the value.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The switch Statement
The switch statement takes the form:
switch (testExpression)
{
case Value_1:
// place one or more statements here
break;
case Value_2:
// place one or more statements here
break;
// case statements may be repeated
//as many times as necessary
default:
// place one or more statements here
}
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The switch Statement
The testExpression is a variable or expression
that gives a char, byte, short, int or string value.
switch (testExpression)
{
…
}
The switch statement will evaluate the
testExpression.
If there is an associated case statement that
matches that value, program execution will be
transferred to that case statement.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The switch Statement
Each case statement will have a corresponding
case value that must be unique.
case value_1:
// place one or more statements here
break;
If the testExpression matches the case value, the
Java statements between the colon and the break
statement will be executed.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The case Statement
The break statement ends the case statement.
The break statement is optional.
If a case does not contain a break, then program
execution continues into the next case.
See example: NoBreaks.java
See example: PetFood.java
The default section is optional and will be
executed if no CaseExpression matches the
SwitchExpression.
See example: SwitchDemo.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The DecimalFormat Class
When printing out double and float values,
the full fractional value will be printed.
The DecimalFormat class can be used to
format these values.
In order to use the DecimalFormat class,
the following import statement must be
used at the top of the program:
import java.text.DecimalFormat;
See examples:
Format1.java, Format2.java, Format3.java, Format4.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The SalesCommission Class
SalesCommision
- sales : double
- rate : double
- commission : double
- advance : double
- pay : double
+ SalesCommission(s: double,
a: double) :
- setRate() : void
-calculatePay() : void
+ getPay() : double
+ getCommission() : double
+ getRate() : double
+ getAdvance() : double
+ getSales() : double
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Method Decomposition
Using Private Methods
Long methods can be broken up into
shorter more specialized methods,
known as helper or utility methods.
Each method should perform a small,
well-defined task.
Sensitive tasks can be broken into
private methods.
Private methods are available only to
other methods within the class.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Main Programs
The SalesCommision class is a utility
class.
It provides an abstraction of the data
and methods needed to calculate a
sales commission.
The program that utilizes this class is
called the Main program.
Example: HalsCommission.java
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Generating Random Numbers with the
Random Class
Some applications, such as games and
simulations, require the use of randomly
generated numbers.
The Java API has a class, Random, for this
purpose. To use the Random class, use the
following import statement and create an
instance of the class.
import java.util.Random;
Random randomNumbers = new Random();
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Some Methods of the Random
Class
Method Description
nextDouble() Returns the next random number as a double. The number
will be within the range of 0.0 and 1.0.
nextFloat() Returns the next random number as a float. The number
will be within the range of 0.0 and 1.0.
nextInt() Returns the next random number as an int. The number
will be within the range of an int, which is –2,147,483,648
to +2,147,483,648.
nextInt(int n) This method accepts an integer argument, n. It returns a
random number as an int. The number will be within the
range of 0 to n.
See examples: MathTutor.java, DiceDemo.java

More Related Content

Similar to Eo gaddis java_chapter_04_5e

Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3dplunkett
 
Fcp chapter 2 upto_if_else (2)
Fcp chapter 2 upto_if_else (2)Fcp chapter 2 upto_if_else (2)
Fcp chapter 2 upto_if_else (2)Jagdish Kamble
 
Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eGina Bullock
 
Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eGina Bullock
 
Java Introduction to Problem Solving.pdf
Java Introduction to Problem Solving.pdfJava Introduction to Problem Solving.pdf
Java Introduction to Problem Solving.pdfpalogjohnjr
 
Chap11 (ICS12).pdf
Chap11 (ICS12).pdfChap11 (ICS12).pdf
Chap11 (ICS12).pdfJounAbbas4
 
Control flow stataements
Control flow stataementsControl flow stataements
Control flow stataementsMitali Chugh
 
Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrayssshhzap
 
Copyright © 2018 Pearson Education, Inc.C H A P T E R 3.docx
Copyright © 2018 Pearson Education, Inc.C H A P T E R  3.docxCopyright © 2018 Pearson Education, Inc.C H A P T E R  3.docx
Copyright © 2018 Pearson Education, Inc.C H A P T E R 3.docxdickonsondorris
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c languagechintupro9
 
Chapter4.pptxbwmwhwhwhwukwhwjwwjjwjwjwuw
Chapter4.pptxbwmwhwhwhwukwhwjwwjjwjwjwuwChapter4.pptxbwmwhwhwhwukwhwjwwjjwjwjwuw
Chapter4.pptxbwmwhwhwhwukwhwjwwjjwjwjwuwcbashirmacalin
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statementsmaznabili
 
nuts and bolts of c++
nuts and bolts of c++nuts and bolts of c++
nuts and bolts of c++guestfb6ada
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)Muhammad Hammad Waseem
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlanDeepak Lakhlan
 

Similar to Eo gaddis java_chapter_04_5e (20)

Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
 
Ch04
Ch04Ch04
Ch04
 
Fcp chapter 2 upto_if_else (2)
Fcp chapter 2 upto_if_else (2)Fcp chapter 2 upto_if_else (2)
Fcp chapter 2 upto_if_else (2)
 
Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5e
 
Eo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5eEo gaddis java_chapter_10_5e
Eo gaddis java_chapter_10_5e
 
Java Introduction to Problem Solving.pdf
Java Introduction to Problem Solving.pdfJava Introduction to Problem Solving.pdf
Java Introduction to Problem Solving.pdf
 
Chap11 (ICS12).pdf
Chap11 (ICS12).pdfChap11 (ICS12).pdf
Chap11 (ICS12).pdf
 
Control flow stataements
Control flow stataementsControl flow stataements
Control flow stataements
 
Chapter 4 flow control structures and arrays
Chapter 4 flow control structures and arraysChapter 4 flow control structures and arrays
Chapter 4 flow control structures and arrays
 
Copyright © 2018 Pearson Education, Inc.C H A P T E R 3.docx
Copyright © 2018 Pearson Education, Inc.C H A P T E R  3.docxCopyright © 2018 Pearson Education, Inc.C H A P T E R  3.docx
Copyright © 2018 Pearson Education, Inc.C H A P T E R 3.docx
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
 
Chapter4.pptxbwmwhwhwhwukwhwjwwjjwjwjwuw
Chapter4.pptxbwmwhwhwhwukwhwjwwjjwjwjwuwChapter4.pptxbwmwhwhwhwukwhwjwwjjwjwjwuw
Chapter4.pptxbwmwhwhwhwukwhwjwwjjwjwjwuw
 
Control Statement programming
Control Statement programmingControl Statement programming
Control Statement programming
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
 
M C6java5
M C6java5M C6java5
M C6java5
 
Flow control in c++
Flow control in c++Flow control in c++
Flow control in c++
 
nuts and bolts of c++
nuts and bolts of c++nuts and bolts of c++
nuts and bolts of c++
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
 
slides03.ppt
slides03.pptslides03.ppt
slides03.ppt
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlan
 

More from Gina Bullock

Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eGina Bullock
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eGina Bullock
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eGina Bullock
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eGina Bullock
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eGina Bullock
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eGina Bullock
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eGina Bullock
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eGina Bullock
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eGina Bullock
 
Eo gaddis java_chapter_16_5e
Eo gaddis java_chapter_16_5eEo gaddis java_chapter_16_5e
Eo gaddis java_chapter_16_5eGina Bullock
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eGina Bullock
 
Eo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5eEo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5eGina Bullock
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eGina Bullock
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eGina Bullock
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eGina Bullock
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eGina Bullock
 
Eo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5eEo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5eGina Bullock
 
Eo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eEo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eGina Bullock
 

More from Gina Bullock (20)

Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5e
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5e
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5e
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Eo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5eEo gaddis java_chapter_04_5e
Eo gaddis java_chapter_04_5e
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5e
 
Eo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5eEo gaddis java_chapter_06_5e
Eo gaddis java_chapter_06_5e
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
 
Eo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5eEo gaddis java_chapter_01_5e
Eo gaddis java_chapter_01_5e
 
Eo gaddis java_chapter_16_5e
Eo gaddis java_chapter_16_5eEo gaddis java_chapter_16_5e
Eo gaddis java_chapter_16_5e
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5e
 
Eo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5eEo gaddis java_chapter_13_5e
Eo gaddis java_chapter_13_5e
 
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5eEo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
 
Eo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5eEo gaddis java_chapter_11_5e
Eo gaddis java_chapter_11_5e
 
Eo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5eEo gaddis java_chapter_09_5e
Eo gaddis java_chapter_09_5e
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
 
Eo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5eEo gaddis java_chapter_02_5e
Eo gaddis java_chapter_02_5e
 
Eo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eEo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5e
 

Recently uploaded

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 

Recently uploaded (20)

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 

Eo gaddis java_chapter_04_5e

  • 1. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C HA PT E R 4 Decision Structures
  • 2. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics The if Statement The if-else Statement The PayRoll class Nested if Statements The if-else-if Statement Logical Operators Comparing String Objects
  • 3. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics (cont’d) More about Variable Declaration and Scope The Conditional Operator The switch Statement The DecimalFormat Class The SalesCommission Class Generating Random Numbers with the Random Class
  • 4. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The if Statement The if statement decides whether a section of code executes or not. The if statement uses a boolean to decide whether the next statement or block of statements executes. if (boolean expression is true) execute next statement.
  • 5. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Flowcharts • If statements can be modeled as a flow chart. Wear a coat. YesIs it cold outside? if (coldOutside) wearCoat();
  • 6. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Flowcharts (cont’d) • A block if statement may be modeled as: Wear a coat. YesIs it cold outside? Wear a hat. Wear gloves. if (coldOutside) { wearCoat(); wearHat(); wearGloves(); } Note the use of curly braces to block several statements together.
  • 7. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Relational Operators • In most cases, the boolean expression, used by the if statement, uses relational operators. Relational Operator Meaning > is greater than < is less than >= is greater than or equal to <= is less than or equal to == is equal to != is not equal to
  • 8. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Boolean Expressions • A boolean expression is any variable or calculation that results in a true or false condition. Expression Meaning x > y Is x greater than y? x < y Is x less than y? x >= y Is x greater than or equal to y? x <= y Is x less than or equal to y. x == y Is x equal to y? x != y Is x not equal to y?
  • 9. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if Statements and Boolean Expressions if (x > y) System.out.println("X is greater than Y"); if(x == y) System.out.println("X is equal to Y"); if(x != y) { System.out.println("X is not equal to Y"); x = y; System.out.println("However, now it is."); } Example: AverageScore.java
  • 10. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Programming Style and if Statements • An if statement can span more than one line; however, it is still one statement. if (average > 95) grade = ′A′; is functionally equivalent to if(average > 95) grade = ′A′;
  • 11. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Programming Style and if Statements (cont’d) • Rules of thumb: – The conditionally executed statement should be on the line after the if condition. – The conditionally executed statement should be indented one level from the if condition. – If an if statement does not have the block curly braces, it is ended by the first semicolon encountered after the if condition. if (expression) statement; No semicolon here. Semicolon ends statement here.
  • 12. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Having Multiple Conditionally- Executed Statements Conditionally executed statements can be grouped into a block by using curly braces {} to enclose them. If curly braces are used to group conditionally executed statements, the if statement is ended by the closing curly brace. if (expression) { statement1; statement2; } Curly brace ends the statement.
  • 13. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Having Multiple Conditionally- Executed Statements (cont’d) Remember that when the curly braces are not used, then only the next statement after the if condition will be executed conditionally. if (expression) statement1; statement2; statement3; Only this statement is conditionally executed.
  • 14. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Flags A flag is a boolean variable that monitors some condition in a program. When a condition is true, the flag is set to true. The flag can be tested to see if the condition has changed. if (average > 95) highScore = true; Later, this condition can be tested: if (highScore) System.out.println("That′s a high score!");
  • 15. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparing Characters Characters can be tested using the relational operators. Characters are stored in the computer using the Unicode character format. Unicode is stored as a sixteen (16) bit number. Characters are ordinal, meaning they have an order in the Unicode character set. Since characters are ordinal, they can be compared to each other. char c = ′A′; if(c < ′Z′) System.out.println("A is less than Z");
  • 16. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if-else Statements The if-else statement adds the ability to conditionally execute code when the if condition is false. if (expression) statementOrBlockIfTrue; else statementOrBlockIfFalse; See example: Division.java
  • 17. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Payroll Class Payroll - hoursWorked : double - payRate : double + Payroll() + setHoursWorked(hours : double) : void + setPayRate(rate : double): void + getHoursWorked() : double + getPayRate() : double + getGrossPay() : double
  • 18. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if-else Statement Flowcharts Wear a coat. YesIs it cold outside? Wear shorts. No
  • 19. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Nested if Statements If an if statement appears inside another if statement (single or block) it is called a nested if statement. The nested if is executed only if the outer if statement results in a true condition. See example: LoanQualifier.java
  • 20. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Nested if Statement Flowcharts Wear a jacket. YesIs it cold outside? Wear shorts. Is it snowing? Wear a parka. No No Yes
  • 21. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if-else Matching Curly brace use is not required if there is only one statement to be conditionally executed. However, sometimes curly braces can help make the program more readable. Additionally, proper indentation makes it much easier to match up else statements with their corresponding if statement.
  • 22. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if-else Matching if (employed == ′y′) { if (recentGrad == ′y′) { System.out.println("You qualify for the " + "special interest rate."); } else { System.out.println("You must be a recent " + "college graduate to qualify."); } } else { System.out.println("You must be employed to qualify."); }
  • 23. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if-else-if Statements if-else-if statements can become very complex. Imagine the following decision set. if it is very cold, wear a heavy coat, else, if it is chilly, wear a light jacket, else, if it is windy wear a windbreaker, else, if it is hot, wear no jacket.
  • 24. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if-else-if Statements if (expression) statement or block else if (expression) statement or block // Put as many else ifs as needed here else statement or block Care must be used since else statements match up with the immediately preceding unmatched if statement. See example: TestGrade.java, TestResults.java
  • 25. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley if-else-if Flowchart
  • 26. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!) logical operator to reverse the truth of a boolean expression.
  • 27. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Logical Operators Operator Meaning Effect && AND Connects two boolean expressions into one. Both expressions must be true for the overall expression to be true. || OR Connects two boolean expressions into one. One or both expressions must be true for the overall expression to be true. It is only necessary for one to be true, and it does not matter which one. ! NOT The ! operator reverses the truth of a boolean expression. If it is applied to an expression that is true, the operator returns false. If it is applied to an expression that is false, the operator returns true.
  • 28. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The && Operator The logical AND operator (&&) takes two operands that must both be boolean expressions. The resulting combined expression is true if (and only if) both operands are true. See example: LogicalAnd.java Expression 1 Expression 2 Expression1 && Expression2 true false false false true false false false false true true true
  • 29. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The || Operator The logical OR operator (||) takes two operands that must both be boolean expressions. The resulting combined expression is false if (and only if) both operands are false. Example: LogicalOr.java Expression 1 Expression 2 Expression1 || Expression2 true false true false true true false false false true true true
  • 30. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The ! Operator The ! operator performs a logical NOT operation. If an expression is true, !expression will be false. if (!(temperature > 100)) System.out.println("Below the maximum temperature."); If temperature > 100 evaluates to false, then the output statement will be run. Expression 1 !Expression1 true false false true
  • 31. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Short Circuiting Logical AND and logical OR operations perform short-circuit evaluation of expressions. Logical AND will evaluate to false as soon as it sees that one of its operands is a false expression. Logical OR will evaluate to true as soon as it sees that one of its operands is a true expression.
  • 32. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Order of Precedence The ! operator has a higher order of precedence than the && and || operators. The && and || operators have a lower precedence than relational operators like < and >. Parenthesis can be used to force the precedence to be changed.
  • 33. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Order of Precedence Order of Precedence Operators Description 1 (unary negation) ! Unary negation, logical NOT 2 * / % Multiplication, Division, Modulus 3 + - Addition, Subtraction 4 < > <= >= Less-than, Greater-than, Less-than or equal to, Greater-than or equal to 5 == != Is equal to, Is not equal to 6 && Logical AND 7 || Logical NOT 8 = += -= *= /= %= Assignment and combined assignment operators.
  • 34. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparing String Objects In most cases, you cannot use the relational operators to compare two String objects. Reference variables contain the address of the object they represent. Unless the references point to the same object, the relational operators will not return true. See example: GoodStringCompare.java See example: StringCompareTo.java
  • 35. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Ignoring Case in String Comparisons In the String class the equals and compareTo methods are case sensitive. In order to compare two String objects that might have different case, use: equalsIgnoreCase compareToIgnoreCase See example: SecretWord.java
  • 36. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Variable Scope In Java, a local variable does not have to be declared at the beginning of the method. The scope of a local variable begins at the point it is declared and terminates at the end of the method. When a program enters a section of code where a variable has scope, that variable has come into scope, which means the variable is visible to the program. See example: VariableScope.java
  • 37. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Conditional Operator The conditional operator is a ternary (three operand) operator. You can use the conditional operator to write a simple statement that works like an if- else statement. The format of the operators is: expression1 ? expression2 : expression3 The conditional operator can also return a value.
  • 38. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Conditional Operator The conditional operator can be used as a shortened if-else statement: x > y ? z = 10 : z = 5; This line is functionally equivalent to: if(x > y) z = 10; else z = 5;
  • 39. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Conditional Operator Many times the conditional operator is used to supply a value. number = x > y ? 10 : 5; This is functionally equivalent to: if(x > y) number = 10; else number = 5; See example: ConsultantCharges.java
  • 40. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The switch Statement The if-else statement allows you to make true / false branches. The switch statement allows you to use an ordinal value to determine how a program will branch. The switch statement can evaluate a char, byte, short, int, or string value and make decisions based on the value.
  • 41. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The switch Statement The switch statement takes the form: switch (testExpression) { case Value_1: // place one or more statements here break; case Value_2: // place one or more statements here break; // case statements may be repeated //as many times as necessary default: // place one or more statements here }
  • 42. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The switch Statement The testExpression is a variable or expression that gives a char, byte, short, int or string value. switch (testExpression) { … } The switch statement will evaluate the testExpression. If there is an associated case statement that matches that value, program execution will be transferred to that case statement.
  • 43. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The switch Statement Each case statement will have a corresponding case value that must be unique. case value_1: // place one or more statements here break; If the testExpression matches the case value, the Java statements between the colon and the break statement will be executed.
  • 44. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The case Statement The break statement ends the case statement. The break statement is optional. If a case does not contain a break, then program execution continues into the next case. See example: NoBreaks.java See example: PetFood.java The default section is optional and will be executed if no CaseExpression matches the SwitchExpression. See example: SwitchDemo.java
  • 45. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The DecimalFormat Class When printing out double and float values, the full fractional value will be printed. The DecimalFormat class can be used to format these values. In order to use the DecimalFormat class, the following import statement must be used at the top of the program: import java.text.DecimalFormat; See examples: Format1.java, Format2.java, Format3.java, Format4.java
  • 46. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The SalesCommission Class SalesCommision - sales : double - rate : double - commission : double - advance : double - pay : double + SalesCommission(s: double, a: double) : - setRate() : void -calculatePay() : void + getPay() : double + getCommission() : double + getRate() : double + getAdvance() : double + getSales() : double
  • 47. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Method Decomposition Using Private Methods Long methods can be broken up into shorter more specialized methods, known as helper or utility methods. Each method should perform a small, well-defined task. Sensitive tasks can be broken into private methods. Private methods are available only to other methods within the class.
  • 48. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Main Programs The SalesCommision class is a utility class. It provides an abstraction of the data and methods needed to calculate a sales commission. The program that utilizes this class is called the Main program. Example: HalsCommission.java
  • 49. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Generating Random Numbers with the Random Class Some applications, such as games and simulations, require the use of randomly generated numbers. The Java API has a class, Random, for this purpose. To use the Random class, use the following import statement and create an instance of the class. import java.util.Random; Random randomNumbers = new Random();
  • 50. Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Some Methods of the Random Class Method Description nextDouble() Returns the next random number as a double. The number will be within the range of 0.0 and 1.0. nextFloat() Returns the next random number as a float. The number will be within the range of 0.0 and 1.0. nextInt() Returns the next random number as an int. The number will be within the range of an int, which is –2,147,483,648 to +2,147,483,648. nextInt(int n) This method accepts an integer argument, n. It returns a random number as an int. The number will be within the range of 0 to n. See examples: MathTutor.java, DiceDemo.java