SlideShare a Scribd company logo
Control Statements
Eric Roberts
CS 106A
January 15, 2010
Once upon a time . . .
Optional Movie
Martin Luther King, Jr.
“I Have a Dream”
Gates B-12
Monday, January 18
3:15P.M.
And so even though we face the difficulties
of today and tomorrow, I still have a dream.
It is a dream deeply rooted in the American
dream.
I have a dream that one day this nation
will rise up and live out the true meaning of
its creed: “We hold these truths to be self-
evident, that all men are created equal.”
Control Statements
The GObject Hierarchy
The classes that represent graphical objects form a hierarchy, part
of which looks like this:
GObject
GRect GOval GLine
GLabel
The GObject class represents the collection of all graphical
objects. The four subclasses shown in this diagram correspond to
particular types of objects: labels, rectangles, ovals, and lines.
The class diagram makes it clear that any GLabel, GRect, GOval,
or GLine is also a GObject.
Operations on graphical objects are defined at each level of the
hierarchy. Operations that apply to all graphical objects are
specified at the GObject level, where they are inherited by each
subclass. Operations that apply to a particular subclass are
specified as part of the definition of that class.
Operations on the GObject Class
object.setColor(color)
Sets the color of the object to the specified color constant.
object.setLocation(x, y)
Changes the location of the object to the point (x, y).
object.move(dx, dy)
Moves the object on the screen by adding dx and dy to its current coordinates.
The following operations apply to all GObjects:
The standard color names are defined in the java.awt package:
Color.BLACK
Color.DARK_GRAY
Color.GRAY
Color.LIGHT_GRAY
Color.WHITE
Color.RED
Color.YELLOW
Color.GREEN
Color.CYAN
Color.BLUE
Color.MAGENTA
Color.ORANGE
Color.PINK
Operations on the GLabel Class
Constructor
new GLabel(text, x, y)
Creates a label containing the specified text that begins at the point (x, y).
Methods specific to the GLabel class
label.setFont(font)
Sets the font used to display the label as specified by the font string.
The font is typically specified as a string in the form
"family-style-size"
where
family is the name of a font family
style is either PLAIN, BOLD, ITALIC, or BOLDITALIC
size is an integer indicating the point size
Drawing Geometrical Objects
Constructors
new GRect( x, y, width, height)
Creates a rectangle whose upper left corner is at (x, y) of the specified size.
new GOval( x, y, width, height)
Creates an oval that fits inside the rectangle with the same dimensions.
Methods shared by the GRect and GOval classes
object.setFilled(fill)
If fill is true, fills in the interior of the object; if false, shows only the outline.
object.setFillColor(color)
Sets the color used to fill the interior, which can be different from the border.
new GLine( x0, y0, x1, y1)
Creates a line extending from (x0, y0) to (x1, y1).
Statement Types in Java
• Programs in Java consist of a set of classes. Those classes
contain methods, and each of those methods consists of a
sequence of statements.
• Statements in Java fall into three basic types:
– Simple statements
– Compound statements
– Control statements
• Simple statements are formed by adding a semicolon to the
end of a Java expression.
• Compound statements (also called blocks) are sequences of
statements enclosed in curly braces.
• Control statements fall into two categories:
– Conditional statements that specify some kind of test
– Iterative statements that specify repetition
Boolean Expressions
George Boole (1791-1871)
In many ways, the most important primitive
type in Java is boolean, even though it is by
far the simplest. The only values in the
boolean domain are true and false, but
these are exactly the values you need if you
want your program to make decisions.
The name boolean comes from the English
mathematician George Boole who in 1854
wrote a book entitled An Investigation into
the Laws of Thought, on Which are Founded
the Mathematical Theories of Logic and
Probabilities. That book introduced a system
of logic that has come to be known as
Boolean algebra, which is the foundation for
the boolean data type.
Boolean Operators
• The operators used with the boolean data type fall into two
categories: relational operators and logical operators.
• There are six relational operators that compare values of other
types and produce a boolean result:
== Equals
< Less than
!= Not equals
<= Less than or equal to
>= Greater than or equal to
> Greater than
For example, the expression n <= 10 has the value true if x is
less than or equal to 10 and the value false otherwise.
p || q means either p or q (or both)
• There are also three logical operators:
&& Logical AND
|| Logical OR
! Logical NOT
p && q means both p and q
!p means the opposite of p
Notes on the Boolean Operators
• Remember that Java uses = to denote assignment. To test
whether two values are equal, you must use the == operator.
• The || operator means either or both, which is not always
clear in the English interpretation of or.
• It is not legal in Java to use more than one relational operator
in a single comparison as is often done in mathematics. To
express the idea embodied in the mathematical expression
0 ≤ x ≤ 9
0 <= x && x <= 9
you need to make both comparisons explicit, as in
• Be careful when you combine the ! operator with && and ||
because the interpretation often differs from informal English.
Short-Circuit Evaluation
• Java evaluates the && and || operators using a strategy called
short-circuit mode in which it evaluates the right operand
only if it needs to do so.
• One of the advantages of short-circuit evaluation is that you
can use && and || to prevent execution errors. If n were 0 in
the earlier example, evaluating x % n would cause a “division
by zero” error.
• For example, if n is 0, the right hand operand of && in
n != 0 && x % n == 0
is not evaluated at all because n != 0 is false. Because the
expression
false && anything
is always false, the rest of the expression no longer matters.
The if Statement
The simplest of the control statements is the if statement, which
occurs in two forms. You use the first form whenever you need
to perform an operation only if a particular condition is true:
if (condition) {
statements to be executed if the condition is true
}
You use the second form whenever you want to choose between
two alternative paths, one for cases in which a condition is true
and a second for cases in which that condition is false:
if (condition) {
statements to be executed if the condition is true
} else {
statements to be executed if the condition is false
}
Common Forms of the if Statement
if (condition) statement
Single line if statement
if (condition) {
statement
. . . more statements . . .
}
Multiline if statement with curly braces
if (condition) {
statementstrue
} else {
statementsfalse
}
if/else statement with curly braces
if (condition1) {
statements1
} else if (condition2) {
statements2
. . . more else/if conditions . . .
} else {
statementselse
}
Cascading if statement
The examples in the book use only the following forms of the if
statement:
The ?: Operator
• In addition to the if statement, Java provides a more compact
way to express conditional execution that can be extremely
useful in certain situations. This feature is called the ?:
operator (pronounced question-mark-colon) and is part of the
expression structure. The ?: operator has the following form:
• When Java evaluates the ?: operator, it first determines the
value of condition, which must be a boolean. If condition is
true, Java evaluates expression1 and uses that as the value; if
condition is false, Java evaluates expression2 instead.
condition ? expression1 : expression2
• You could use the ?: operator to assign the larger of x and y
to the variable max like this:
max = (x > y) ? x : y;
The switch Statement
The switch statement provides a convenient syntax for choosing
among a set of possible paths:
When Java executes a switch statement, it begins by evaluating
expression, which must produce an integer-like value.
Java then looks for a case clause that matches expression. If
expression was equal to v2, Java would choose the second clause.
Java evaluates the statements in a case clause until it reaches the
break statement, which should appear at the end of each clause.
If none of the values in the case clauses match the expression,
Java evaluates the statements in the default clause.
switch ( expression ) {
case v1:
statements to be executed if expression = v1
break;
case v2:
statements to be executed if expression = v2
break;
. . . more case clauses if needed . . .
default:
statements to be executed if no values match
break;
}
The switch statement provides a convenient syntax for choosing
among a set of possible paths:
switch ( expression ) {
case v1:
statements to be executed if expression = v1
break;
case v2:
statements to be executed if expression = v2
break;
. . . more case clauses if needed . . .
default:
statements to be executed if no values match
break;
}
Example of the switch Statement
public void run() {
println(This program shows the number of days in a month.");
int month = readInt("Enter numeric month (Jan=1): ");
switch (month) {
case 2:
println("28 days (29 in leap years)");
break;
case 4: case 6: case 9: case 11:
println("30 days");
break;
case 1: case 3: case 5: case 7: case 8: case 12:
println("31 days");
break;
default:
println("Illegal month number");
break;
}
}
The switch statement is useful when the program must choose
among several cases, as in the following example:
The while Statement
The while statement is the simplest of Java’s iterative control
statements and has the following form:
while ( condition ) {
statements to be repeated
}
When Java encounters a while statement, it begins by evaluating
the condition in parentheses, which must have a boolean value.
If the value of condition is true, Java executes the statements in
the body of the loop.
At the end of each cycle, Java reevaluates condition to see
whether its value has changed. If condition evaluates to false,
Java exits from the loop and continues with the statement
following the closing brace at the end of the while body.
while ( condition ) {
statements to be repeated
}
The DigitSum Program
public void run() {
println("This program sums the digits in an integer.");
int n = readInt("Enter a positive integer: ");
int dsum = 0;
while ( n > 0 ) {
dsum += n % 10;
n /= 10;
}
println("The sum of the digits is " + dsum);
}
DigitSum
n dsum
0
1729 9
172 11
17 18
1
This program sums the digits in an integer.
The sum of the digits is 19.
1729
Enter a positive integer:
19
0
public void run() {
println("This program sums the digits in an integer.");
int n = readInt("Enter a positive integer: ");
int dsum = 0;
while ( n > 0 ) {
dsum += n % 10;
n /= 10;
}
println("The sum of the digits is " + dsum);
}
n dsum
19
0
public void run() {
println("This program sums the digits in an integer.");
int n = readInt("Enter a positive integer: ");
int dsum = 0;
while ( n > 0 ) {
dsum += n % 10;
n /= 10;
}
println("The sum of the digits is " + dsum);
}
skip simulation
The for Statement
The for statement in Java is a particularly powerful tool for
specifying the control structure of a loop independently from the
operations the loop body performs. The syntax looks like this:
for ( init ; test ; step ) {
statements to be repeated
}
Java evaluates a for statement by executing the following steps:
Evaluate init, which typically declares a control variable.
1.
Evaluate test and exit from the loop if the value is false.
2.
Execute the statements in the body of the loop.
3.
Evaluate step, which usually updates the control variable.
4.
Return to step 2 to begin the next loop cycle.
5.
for ( init ; test ; step ) {
statements to be repeated
}
Comparing for and while
The for statement
is functionally equivalent to the following code using while:
for ( init ; test ; step ) {
statements to be repeated
}
init;
while ( test ) {
statements to be repeated
step;
}
The advantage of the for statement is that everything you need to
know to understand how many times the loop will run is
explicitly included in the header line.
Exercise: Reading for Statements
Describe the effect of each of the following for statements:
This statement executes the loop body ten times, with the control
variable i taking on each successive value between 1 and 10.
for (int i = 1; i <= 10; i++)
1.
This statement executes the loop body N times, with i counting from
0 to N-1. This version is the standard Repeat-N-Times idiom.
for (int i = 0; i < N; i++)
2.
This statement counts backward from 99 to 1 by twos.
for (int n = 99; n >= 1; n -= 2)
3.
This statement executes the loop body with the variable x taking on
successive powers of two from 1 up to 1024.
for (int x = 1; x <= 1024; x *= 2)
4.
The Checkerboard Program
public void run() {
double sqSize = (double) getHeight() / N_ROWS;
for (int i = 0; i < N_ROWS; i++) {
for (int j = 0; j < N_COLUMNS; j++) {
double x = j * sqSize;
double y = i * sqSize;
GRect sq = new GRect(x, y, sqSize, sqSize);
sq.setFilled((i + j) % 2 != 0);
add(sq);
}
}
}
sq
y
x
j
i
sqSize
30.0 0 0 0.0 0.0
30.0
1
1 60.0
2 210.0
8
8 210.0
Execute the
inner loop
seven times to
complete the
checkerboard.
Execute these
statements six
more times to
complete the
row.
public void run() {
double sqSize = (double) getHeight() / N_ROWS;
for (int i = 0; i < N_ROWS; i++) {
for (int j = 0; j < N_COLUMNS; j++) {
double x = j * sqSize;
double y = i * sqSize;
GRect sq = new GRect(x, y, sqSize, sqSize);
sq.setFilled((i + j) % 2 != 0);
add(sq);
}
}
}
sq
y
x
j
i
sqSize
30.0 210.0
8
8 210.0
skip simulation
Checkerboard
Simple Graphical Animation
The while and for statements make it possible to implement
simple graphical animation. The basic strategy is to create a set
of graphical objects and then execute the following loop:
for (int i = 0; i < N_STEPS; i++) {
update the graphical objects by a small amount
pause(PAUSE_TIME);
}
On each cycle of the loop, this pattern updates each animated
object by moving it slightly or changing some other property of
the object, such as its color. Each cycle is called a time step.
After each time step, the animation pattern calls pause, which
delays the program for some number of milliseconds (expressed
here as the constant PAUSE_TIME). Without the call to pause, the
program would finish faster than the human eye can follow.
for (int i = 0; i < N_STEPS; i++) {
update the graphical objects by a small amount
pause(PAUSE_TIME);
}
AnimatedSquare
The AnimatedSquare Program
public void run() {
GRect square = new GRect(0, 0, SQUARE_SIZE, SQUARE_SIZE);
square.setFilled(true);
square.setFillColor(Color.RED);
add(square);
double dx = (getWidth() - SQUARE_SIZE) / N_STEPS;
double dy = (getHeight() - SQUARE_SIZE) / N_STEPS;
for (int i = 0; i < N_STEPS; i++) {
square.move(dx, dy);
pause(PAUSE_TIME);
}
}
square
dy
dx
3.0 1.7
AnimatedSquare
skip simulation
i
public void run() {
GRect square = new GRect(0, 0, SQUARE_SIZE, SQUARE_SIZE);
square.setFilled(true);
square.setFillColor(Color.RED);
add(square);
double dx = (getWidth() - SQUARE_SIZE) / N_STEPS;
double dy = (getHeight() - SQUARE_SIZE) / N_STEPS;
for (int i = 0; i < N_STEPS; i++) {
square.move(dx, dy);
pause(PAUSE_TIME);
}
}
square
dy
dx
3.0 1.7
AnimatedSquare
i
101
The End

More Related Content

PPTX
MODULE_2_Operators.pptx
PPT
M C6java5
PDF
data types.pdf
PPTX
Introduction to Java
PPT
slides03.ppt
PDF
Java input Scanner
PPT
Chapter 2&3 (java fundamentals and Control Structures).ppt
PDF
CIS 1403 lab 4 selection
MODULE_2_Operators.pptx
M C6java5
data types.pdf
Introduction to Java
slides03.ppt
Java input Scanner
Chapter 2&3 (java fundamentals and Control Structures).ppt
CIS 1403 lab 4 selection

Similar to 06-ControlStatements in Java Loops, If statements, Switch.ppt (20)

PPTX
Chap3java5th
PDF
java notes.pdf
PPTX
Java chapter 3
PPT
PPTX
130706266060138191
PPTX
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
PPTX
PPTX
ChapterTwoandThreefnfgncvdjhgjshgjdlahgjlhglj.pptx
PPT
Switch and control statement for c language
PPT
Switch and control looping statement for C
PPT
Switch and looping statement for c language
PPTX
Pi j1.3 operators
PPT
Introduction to java programming part 2
PPTX
ICSE Class X Conditional Statements in java
PPT
00_Introduction to Java.ppt
PDF
Lecture1.pdf
PPTX
Flow of control by deepak lakhlan
PPT
Chapter 3 Selection of Java Chapter 3 Selection of Java
PPTX
Java class 1
Chap3java5th
java notes.pdf
Java chapter 3
130706266060138191
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
ChapterTwoandThreefnfgncvdjhgjshgjdlahgjlhglj.pptx
Switch and control statement for c language
Switch and control looping statement for C
Switch and looping statement for c language
Pi j1.3 operators
Introduction to java programming part 2
ICSE Class X Conditional Statements in java
00_Introduction to Java.ppt
Lecture1.pdf
Flow of control by deepak lakhlan
Chapter 3 Selection of Java Chapter 3 Selection of Java
Java class 1
Ad

More from javidmiakhil63 (7)

PPTX
Lecture_1_Introduction_to_Operating_Systems.pptx
PPTX
Lecture_2_Process_Management in operating systems.pptx
PPTX
Lec 2 Compiler, Interpreter, linker, loader.pptx
PPTX
Lec 1 Introduction to Programming Concepts.pptx
PPT
24-BuildingGUIs Complete Materials in Java.ppt
PPT
java_lect_05 Constructors in Java with overloading.ppt
PPT
java_lect_04 Decision Structures in Java.ppt
Lecture_1_Introduction_to_Operating_Systems.pptx
Lecture_2_Process_Management in operating systems.pptx
Lec 2 Compiler, Interpreter, linker, loader.pptx
Lec 1 Introduction to Programming Concepts.pptx
24-BuildingGUIs Complete Materials in Java.ppt
java_lect_05 Constructors in Java with overloading.ppt
java_lect_04 Decision Structures in Java.ppt
Ad

Recently uploaded (20)

PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Digital Strategies for Manufacturing Companies
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Nekopoi APK 2025 free lastest update
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
L1 - Introduction to python Backend.pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
ai tools demonstartion for schools and inter college
Which alternative to Crystal Reports is best for small or large businesses.pdf
Understanding Forklifts - TECH EHS Solution
Design an Analysis of Algorithms II-SECS-1021-03
wealthsignaloriginal-com-DS-text-... (1).pdf
VVF-Customer-Presentation2025-Ver1.9.pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Digital Strategies for Manufacturing Companies
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Odoo POS Development Services by CandidRoot Solutions
Reimagine Home Health with the Power of Agentic AI​
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Nekopoi APK 2025 free lastest update
Upgrade and Innovation Strategies for SAP ERP Customers
L1 - Introduction to python Backend.pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Odoo Companies in India – Driving Business Transformation.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
2025 Textile ERP Trends: SAP, Odoo & Oracle
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
ai tools demonstartion for schools and inter college

06-ControlStatements in Java Loops, If statements, Switch.ppt

  • 1. Control Statements Eric Roberts CS 106A January 15, 2010
  • 2. Once upon a time . . .
  • 3. Optional Movie Martin Luther King, Jr. “I Have a Dream” Gates B-12 Monday, January 18 3:15P.M. And so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream. I have a dream that one day this nation will rise up and live out the true meaning of its creed: “We hold these truths to be self- evident, that all men are created equal.”
  • 5. The GObject Hierarchy The classes that represent graphical objects form a hierarchy, part of which looks like this: GObject GRect GOval GLine GLabel The GObject class represents the collection of all graphical objects. The four subclasses shown in this diagram correspond to particular types of objects: labels, rectangles, ovals, and lines. The class diagram makes it clear that any GLabel, GRect, GOval, or GLine is also a GObject. Operations on graphical objects are defined at each level of the hierarchy. Operations that apply to all graphical objects are specified at the GObject level, where they are inherited by each subclass. Operations that apply to a particular subclass are specified as part of the definition of that class.
  • 6. Operations on the GObject Class object.setColor(color) Sets the color of the object to the specified color constant. object.setLocation(x, y) Changes the location of the object to the point (x, y). object.move(dx, dy) Moves the object on the screen by adding dx and dy to its current coordinates. The following operations apply to all GObjects: The standard color names are defined in the java.awt package: Color.BLACK Color.DARK_GRAY Color.GRAY Color.LIGHT_GRAY Color.WHITE Color.RED Color.YELLOW Color.GREEN Color.CYAN Color.BLUE Color.MAGENTA Color.ORANGE Color.PINK
  • 7. Operations on the GLabel Class Constructor new GLabel(text, x, y) Creates a label containing the specified text that begins at the point (x, y). Methods specific to the GLabel class label.setFont(font) Sets the font used to display the label as specified by the font string. The font is typically specified as a string in the form "family-style-size" where family is the name of a font family style is either PLAIN, BOLD, ITALIC, or BOLDITALIC size is an integer indicating the point size
  • 8. Drawing Geometrical Objects Constructors new GRect( x, y, width, height) Creates a rectangle whose upper left corner is at (x, y) of the specified size. new GOval( x, y, width, height) Creates an oval that fits inside the rectangle with the same dimensions. Methods shared by the GRect and GOval classes object.setFilled(fill) If fill is true, fills in the interior of the object; if false, shows only the outline. object.setFillColor(color) Sets the color used to fill the interior, which can be different from the border. new GLine( x0, y0, x1, y1) Creates a line extending from (x0, y0) to (x1, y1).
  • 9. Statement Types in Java • Programs in Java consist of a set of classes. Those classes contain methods, and each of those methods consists of a sequence of statements. • Statements in Java fall into three basic types: – Simple statements – Compound statements – Control statements • Simple statements are formed by adding a semicolon to the end of a Java expression. • Compound statements (also called blocks) are sequences of statements enclosed in curly braces. • Control statements fall into two categories: – Conditional statements that specify some kind of test – Iterative statements that specify repetition
  • 10. Boolean Expressions George Boole (1791-1871) In many ways, the most important primitive type in Java is boolean, even though it is by far the simplest. The only values in the boolean domain are true and false, but these are exactly the values you need if you want your program to make decisions. The name boolean comes from the English mathematician George Boole who in 1854 wrote a book entitled An Investigation into the Laws of Thought, on Which are Founded the Mathematical Theories of Logic and Probabilities. That book introduced a system of logic that has come to be known as Boolean algebra, which is the foundation for the boolean data type.
  • 11. Boolean Operators • The operators used with the boolean data type fall into two categories: relational operators and logical operators. • There are six relational operators that compare values of other types and produce a boolean result: == Equals < Less than != Not equals <= Less than or equal to >= Greater than or equal to > Greater than For example, the expression n <= 10 has the value true if x is less than or equal to 10 and the value false otherwise. p || q means either p or q (or both) • There are also three logical operators: && Logical AND || Logical OR ! Logical NOT p && q means both p and q !p means the opposite of p
  • 12. Notes on the Boolean Operators • Remember that Java uses = to denote assignment. To test whether two values are equal, you must use the == operator. • The || operator means either or both, which is not always clear in the English interpretation of or. • It is not legal in Java to use more than one relational operator in a single comparison as is often done in mathematics. To express the idea embodied in the mathematical expression 0 ≤ x ≤ 9 0 <= x && x <= 9 you need to make both comparisons explicit, as in • Be careful when you combine the ! operator with && and || because the interpretation often differs from informal English.
  • 13. Short-Circuit Evaluation • Java evaluates the && and || operators using a strategy called short-circuit mode in which it evaluates the right operand only if it needs to do so. • One of the advantages of short-circuit evaluation is that you can use && and || to prevent execution errors. If n were 0 in the earlier example, evaluating x % n would cause a “division by zero” error. • For example, if n is 0, the right hand operand of && in n != 0 && x % n == 0 is not evaluated at all because n != 0 is false. Because the expression false && anything is always false, the rest of the expression no longer matters.
  • 14. The if Statement The simplest of the control statements is the if statement, which occurs in two forms. You use the first form whenever you need to perform an operation only if a particular condition is true: if (condition) { statements to be executed if the condition is true } You use the second form whenever you want to choose between two alternative paths, one for cases in which a condition is true and a second for cases in which that condition is false: if (condition) { statements to be executed if the condition is true } else { statements to be executed if the condition is false }
  • 15. Common Forms of the if Statement if (condition) statement Single line if statement if (condition) { statement . . . more statements . . . } Multiline if statement with curly braces if (condition) { statementstrue } else { statementsfalse } if/else statement with curly braces if (condition1) { statements1 } else if (condition2) { statements2 . . . more else/if conditions . . . } else { statementselse } Cascading if statement The examples in the book use only the following forms of the if statement:
  • 16. The ?: Operator • In addition to the if statement, Java provides a more compact way to express conditional execution that can be extremely useful in certain situations. This feature is called the ?: operator (pronounced question-mark-colon) and is part of the expression structure. The ?: operator has the following form: • When Java evaluates the ?: operator, it first determines the value of condition, which must be a boolean. If condition is true, Java evaluates expression1 and uses that as the value; if condition is false, Java evaluates expression2 instead. condition ? expression1 : expression2 • You could use the ?: operator to assign the larger of x and y to the variable max like this: max = (x > y) ? x : y;
  • 17. The switch Statement The switch statement provides a convenient syntax for choosing among a set of possible paths: When Java executes a switch statement, it begins by evaluating expression, which must produce an integer-like value. Java then looks for a case clause that matches expression. If expression was equal to v2, Java would choose the second clause. Java evaluates the statements in a case clause until it reaches the break statement, which should appear at the end of each clause. If none of the values in the case clauses match the expression, Java evaluates the statements in the default clause. switch ( expression ) { case v1: statements to be executed if expression = v1 break; case v2: statements to be executed if expression = v2 break; . . . more case clauses if needed . . . default: statements to be executed if no values match break; } The switch statement provides a convenient syntax for choosing among a set of possible paths: switch ( expression ) { case v1: statements to be executed if expression = v1 break; case v2: statements to be executed if expression = v2 break; . . . more case clauses if needed . . . default: statements to be executed if no values match break; }
  • 18. Example of the switch Statement public void run() { println(This program shows the number of days in a month."); int month = readInt("Enter numeric month (Jan=1): "); switch (month) { case 2: println("28 days (29 in leap years)"); break; case 4: case 6: case 9: case 11: println("30 days"); break; case 1: case 3: case 5: case 7: case 8: case 12: println("31 days"); break; default: println("Illegal month number"); break; } } The switch statement is useful when the program must choose among several cases, as in the following example:
  • 19. The while Statement The while statement is the simplest of Java’s iterative control statements and has the following form: while ( condition ) { statements to be repeated } When Java encounters a while statement, it begins by evaluating the condition in parentheses, which must have a boolean value. If the value of condition is true, Java executes the statements in the body of the loop. At the end of each cycle, Java reevaluates condition to see whether its value has changed. If condition evaluates to false, Java exits from the loop and continues with the statement following the closing brace at the end of the while body. while ( condition ) { statements to be repeated }
  • 20. The DigitSum Program public void run() { println("This program sums the digits in an integer."); int n = readInt("Enter a positive integer: "); int dsum = 0; while ( n > 0 ) { dsum += n % 10; n /= 10; } println("The sum of the digits is " + dsum); } DigitSum n dsum 0 1729 9 172 11 17 18 1 This program sums the digits in an integer. The sum of the digits is 19. 1729 Enter a positive integer: 19 0 public void run() { println("This program sums the digits in an integer."); int n = readInt("Enter a positive integer: "); int dsum = 0; while ( n > 0 ) { dsum += n % 10; n /= 10; } println("The sum of the digits is " + dsum); } n dsum 19 0 public void run() { println("This program sums the digits in an integer."); int n = readInt("Enter a positive integer: "); int dsum = 0; while ( n > 0 ) { dsum += n % 10; n /= 10; } println("The sum of the digits is " + dsum); } skip simulation
  • 21. The for Statement The for statement in Java is a particularly powerful tool for specifying the control structure of a loop independently from the operations the loop body performs. The syntax looks like this: for ( init ; test ; step ) { statements to be repeated } Java evaluates a for statement by executing the following steps: Evaluate init, which typically declares a control variable. 1. Evaluate test and exit from the loop if the value is false. 2. Execute the statements in the body of the loop. 3. Evaluate step, which usually updates the control variable. 4. Return to step 2 to begin the next loop cycle. 5. for ( init ; test ; step ) { statements to be repeated }
  • 22. Comparing for and while The for statement is functionally equivalent to the following code using while: for ( init ; test ; step ) { statements to be repeated } init; while ( test ) { statements to be repeated step; } The advantage of the for statement is that everything you need to know to understand how many times the loop will run is explicitly included in the header line.
  • 23. Exercise: Reading for Statements Describe the effect of each of the following for statements: This statement executes the loop body ten times, with the control variable i taking on each successive value between 1 and 10. for (int i = 1; i <= 10; i++) 1. This statement executes the loop body N times, with i counting from 0 to N-1. This version is the standard Repeat-N-Times idiom. for (int i = 0; i < N; i++) 2. This statement counts backward from 99 to 1 by twos. for (int n = 99; n >= 1; n -= 2) 3. This statement executes the loop body with the variable x taking on successive powers of two from 1 up to 1024. for (int x = 1; x <= 1024; x *= 2) 4.
  • 24. The Checkerboard Program public void run() { double sqSize = (double) getHeight() / N_ROWS; for (int i = 0; i < N_ROWS; i++) { for (int j = 0; j < N_COLUMNS; j++) { double x = j * sqSize; double y = i * sqSize; GRect sq = new GRect(x, y, sqSize, sqSize); sq.setFilled((i + j) % 2 != 0); add(sq); } } } sq y x j i sqSize 30.0 0 0 0.0 0.0 30.0 1 1 60.0 2 210.0 8 8 210.0 Execute the inner loop seven times to complete the checkerboard. Execute these statements six more times to complete the row. public void run() { double sqSize = (double) getHeight() / N_ROWS; for (int i = 0; i < N_ROWS; i++) { for (int j = 0; j < N_COLUMNS; j++) { double x = j * sqSize; double y = i * sqSize; GRect sq = new GRect(x, y, sqSize, sqSize); sq.setFilled((i + j) % 2 != 0); add(sq); } } } sq y x j i sqSize 30.0 210.0 8 8 210.0 skip simulation Checkerboard
  • 25. Simple Graphical Animation The while and for statements make it possible to implement simple graphical animation. The basic strategy is to create a set of graphical objects and then execute the following loop: for (int i = 0; i < N_STEPS; i++) { update the graphical objects by a small amount pause(PAUSE_TIME); } On each cycle of the loop, this pattern updates each animated object by moving it slightly or changing some other property of the object, such as its color. Each cycle is called a time step. After each time step, the animation pattern calls pause, which delays the program for some number of milliseconds (expressed here as the constant PAUSE_TIME). Without the call to pause, the program would finish faster than the human eye can follow. for (int i = 0; i < N_STEPS; i++) { update the graphical objects by a small amount pause(PAUSE_TIME); }
  • 26. AnimatedSquare The AnimatedSquare Program public void run() { GRect square = new GRect(0, 0, SQUARE_SIZE, SQUARE_SIZE); square.setFilled(true); square.setFillColor(Color.RED); add(square); double dx = (getWidth() - SQUARE_SIZE) / N_STEPS; double dy = (getHeight() - SQUARE_SIZE) / N_STEPS; for (int i = 0; i < N_STEPS; i++) { square.move(dx, dy); pause(PAUSE_TIME); } } square dy dx 3.0 1.7 AnimatedSquare skip simulation i public void run() { GRect square = new GRect(0, 0, SQUARE_SIZE, SQUARE_SIZE); square.setFilled(true); square.setFillColor(Color.RED); add(square); double dx = (getWidth() - SQUARE_SIZE) / N_STEPS; double dy = (getHeight() - SQUARE_SIZE) / N_STEPS; for (int i = 0; i < N_STEPS; i++) { square.move(dx, dy); pause(PAUSE_TIME); } } square dy dx 3.0 1.7 AnimatedSquare i 101