You are on page 1of 9

Chapter 5 - Control statements:

3 categories: Selection (if, Switch)


Iteration :(while, do-while, for)
Jump :( break, continue, return)

Java’s selection statements:


Program execution based upon conditions
known only during run time.
If: if (condition) statement1;
else statement2;
condition returns Boolean value.
else clause is optional.
Nested ifs: (target of another if or else)

Season is bogue month.


Another example

If-else-if Ladder: (sequence of nested ifs)


if(condition) statement;
else if(condition) statement;
else if(condition)statement;
......
else statement;

The statements associated with the case constant


that matches i are executed. All others are
bypassed. Switch test-variable didn’t match with
case values then Default is executed 3 times.
4th month is spring.
SWITCH: (multiway branch statement)
Alternate to if-else-if statement
Dispatch execution to different parts of code
based on the value of expression.
No case value matches the value of expression It is important to recognize that the statement or
then do default statement. statement block, associated with each case
option must be terminated by the break
keyword. If you omit the break, execution will
continue on in to the next case. It is sometimes
desirable to have multiple cases without break
statements. (case executed the same statements
if matched)

Use a string to control a switch statement.


Switching on strings can be expensive then
switching on integers.

Default is optional:
Instead of default the result variable num in
initialized to 31.

S is three.
(controlling data s in string form)
Nested switch statement:

ITERATION STATEMENT:

Output: 2/2016: 29 days.

If didn’t initialize the num result variable then use


default statement to avoid compile error.

Output: 1/2016:31 days.


Condition fails so body of loop is not executed.
------------------------------------------------------------

The midvalue is 150.

do-while:
body of the loop executed at least once

For loop:

Output: tick 2 Two forms: for loop, for-each (enhanced for)


tick 1
do-while to process a menu selection:

If one statement no {} needed. When the loop


first starts, the initialization portion of the loop
executed-used to set the value of the loop
control variable (acts as a counter that controls
the loop). Initialization expression is executed
only once. Next, condition is evaluated, must be
a Boolean expression. (tests the loop control
variable against a target value.) true – body
executed, false-loop terminates.
Next iteration portion is executed. Then again
check the condition, execute body then Loop Variations
iteration portion and goes on till the condition 1. Conditional expression does not need
false. to test the loop control variable against
some target value. It can be any
Boolean expression.

Another example

For loop continues to run until the boolean


variable done is set to true. It doesn’t test the
value of i.
2. Initialization and iteration expressions
have been moved out of for.

5 prime.
Loop is controlled by interaction of two variable

if the initial condition is set through a complex


expression elsewhere in the program or if the loop
control variable changes in a nonsequential
manner determined by actions that occur within
the body of the loop, it may be appropriate to
leave these parts of the for empty.
14 3. Intentionally create an infinite loop
23

USING COMMA:
Loop run forever- no condition under which it will
terminate. Some programs such as operating
system command processors require infinite loop.
Infinite loops are just loops with special
termination requirements. The syntax streamlined and prevents boundary
errors.
“For-each” style loop or Enhanced loop: Iteration variable is “read-only” as it relates to the
for-each style loop is designed to cycle through a underlying array. can’t change the contents of the
collection of objects, such as an array, in strictly array by assigning the iteration
sequential fashion, from start to finish.

for(type itr-var : collection) statement-block

itr-var specifies the name of an iteration variable


that will receive the elements from a collection,
one at a time, from beginning to end .With each
iteration of the loop, the next element in the
collection is retrieved and stored in itr-var. The
loop repeats until all elements in the collection
have been obtained
traditional for- manually indexing the nums Output:
array by i (the loop control variable) 1 2 3 4 5 6 7 8 9 10.(when first for executes)
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 1 2 3 4 5 6 7 8 9 10.(when second for executes)
int sum = 0; Iterating over Multidimensional array.
for(int i=0; i < 10; i++) sum += nums[i]; multidimensional arrays consist of arrays of
“for-each style: eliminates the need to arrays. For example, a two-dimensional array is an
establish a loop counter, specify a starting and array of one-dimensional arrays. In the case of a
ending value, and manually index the array. two-dimensional array, the iteration variable must
it automatically cycles through the entire array, be a reference to a one-dimensional array. In
obtaining one element at a time, in sequence, general, when using the for-each for to iterate
from beginning to end. over an array of N dimensions, the objects
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; obtained will be arrays of N–1 dimensions.
int sum = 0;
for(int x: nums) sum += x;
With each pass through the loop, x is
automatically given a value equal to the
next element in nums. Thus, on the first
iteration, x contains 1; on the second
iteration, x contains 2; and so on.
Output-Values of x: 2.5 5.0 10.0 20.0 40.0 80.0
Values in nums array: 1 2 3 4 5 6
for(var x = 2.5; x < 100.0; x = x * 2)
is inferred to be type double because that is the
type of its initializer.
for(var v : nums)
for(int x[]: nums) {
Iteration variable v inferred to be of type int
Notice how x is declared. It is a reference to a one-
because that is the element type of the array
dimensional array of integers. This is necessary
nums.
because each iteration of the for obtains the next
Nested for Loops:( one loop be inside another)
array in nums, beginning with the array specified
by nums[0]. For(int y :x)The inner for loop then
cycles through each of these arrays, displaying the
values of each element.
Search using Enhanced for:

output
..........
.........
........
.......
......
for loop to search an unsorted array for a value
.....
(examining each element in sequence) if the array ....
were sorted, a binary search could be used, which ...
would require a different style loop. It is used for ..
computing an average, finding the minimum or .
maximum of a set, looking for duplicates
JUMP STATEMENTS:
LOCAL VARIABLE TYPE INFERENCE IN A FOR
Break, continue and return
LOOP.
These statements transfer control to another part
The type of a local variable to be inferred from
of your program.(also through exception handling)
the type of its initializer.a
Break:
Force immediate termination of a loop, bypassing
the conditional expression and any remaining
code in the body of the loop. program
control resumes at the next statement following
the loop.
Outerloop run for three times, inner loop
shoud have run for 100 times due to break
statement it terminate when j=10.

More than one break statements may appear


in a loop and the break that terminates a
switch statement affects only that switch
statement and any enclosing loops (normal
although the for loop is designed to run from 0 to loop (for etc) is terminated by conditional
99, the break statement causes it to terminate early, expression. break is used under some special
when i equals 10. situation occurs.
The break statement can be used with any of Using break as a form of Goto:
Java’s loops, including intentionally infinite loops. Java does not have goto statement(unstructured-
hard to understand, hard to maintain, prohibits
compiler optimizations)useful-when u are exiting
from a deeply nested set of loops. So java provides
extended form of the break statement(break with
label) general form :break label;
Break out of one or more blocks of code
(these blocks need not be part of a loop or a switch.
They can be any block.)
Specify precisely where execution will resume.

label (any java identifier followed by : ) identifies a


block of code, put a label name at the start of it.use
Break in Nested loops label as target of a break statement.
After execution (label-break) control is transferred
out of named block that encloses the break
statement. Execution resumes at the the end of the
labeled block.

The break statement will only break out of


the innermost loop. The outer loop is
unaffected. Output: Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9 Before the break.
Pass 1: 0 1 2 3 4 5 6 7 8 9 This is after second block.
Pass 2: 0 1 2 3 4 5 6 7 8 9 Execution starts here system.out.println(“This
Loops complete. is after second break.”)
This code uses the % operator to check if i is even.
labeled break statement (outer)is to exit If it is, the loop continues without printing a
form nested loops. Output: newline.(Bypass println(“”). Output
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete. 01
when the inner loop breaks to the outer loop, 23
both loops have been terminated. Here labels the 45
for statement, which has a block of code as its 67
target. 89
you cannot break to any label which is not Continue with Label:
defined for an enclosing block. For example, the continue specify a label to describe which
enclosing loop to continue. using continue print a
following program is invalid and will not
triangular multiplication table for 0 through 9:
compile:

Since the loop labeled one does not enclose the 0


break statement, it is not possible to transfer 01
control out of that block.
024
USING CONTINUE:
It is useful to force an early iteration of a loop. you 0369
want to continue running the loop but stop 0 4 8 12 16
processing the remainder of the code 0 5 10 15 20 25
in its body for this particular iteration. 0 6 12 18 24 30 36
The continue statement performs such an action. 0 7 14 21 28 35 42 49
In while and do-while loops, a continue statement 0 8 16 24 32 40 48 56 64
causes control to be transferred directly 0 9 18 27 36 45 54 63 72 81
to the conditional expression that controls the Good uses of continue are rare. One reason is that Java
loop. In a for provides a rich set of loop statements which fit most
loop, control goes first to the iteration portion of applications. However, for those special circumstances in
the for statement and then to the conditional which early iteration is needed, the continue statement
expression. For all three loops, any intermediate provides a structured way to accomplish it.
code is bypassed.
Uses continue to cause two numbers to be
printed on each line:
return
The last control statement is return. The return
statement is used to explicitly return from a
method. That is, it causes program control to
transfer back to the caller of the method. As such,
it is categorized as a jump statement.
the return statement immediately terminates the
method in which it is executed.

Output: Before the return


As you can see, the final println( ) statement is not
executed. As soon as return is executed, control
passes back to the caller.
the if(t) statement is necessary. Without it, the Java
compiler would flag an “unreachable code” error
because the compiler would know that the last
println( ) statement would never be executed. To
prevent this error, the if statement is used here to
trick the compiler for the sake of this demonstration.

You might also like