Date post: | 30-May-2018 |
Category: |
Documents |
Upload: | javier-solis |
View: | 219 times |
Download: | 0 times |
of 40
8/9/2019 ComputerScienceReference-StatementControl
1/40
4. Statement Control
4. 1. Statement( 8 ) 4. 8. Break Statement( 5 )
4. 2. If Statement( 9 ) 4. 9. Continue Statement( 4 )
4. 3. Switch Statement( 6 ) 4. 10. try catch( 6 )
4. 4. While Loop( 4 ) 4. 11. throw( 2 )4. 5. Do While Loop( 2 ) 4. 12. finally( 1 )
4. 6. For Loop( 14 ) 4. 13. throws signature( 1 )
4. 7. For Each Loop( 8 )
4. 1. Statement4. 1. 1. An Overview of Java Statements
4. 1. 2. Expressions
4. 1. 3. Declaring and defining multiple variables in a single statement4. 1. 4. Label a statement block
4. 1. 5. Spreading a single declaration over several lines4. 1. 6. How to write multiple assignments in a single statement4. 1. 7. Combining both statements into one
4. 1. 8. Statement Blocks
4. 1. 1. An Overview of Java StatementsIn programming, a statement is an instruction to do something.
It controls the sequence of execution of a program.
In Java, a statement is terminated with a semicolon and multiple statements can be written on a single line.
x = y + 1; z = y + 2;In Java, an empty statement is legal and does nothing: ;
4. 1. 2. ExpressionsSome expressions can be made statements by terminating them with a semicolon. For example, x++ is an
expression. However, this is a statement:
x++;
Statements can be grouped in a block. A block is a sequence of the following programming elements within braces:
statements
local class declarationslocal variable declaration statements
4. 1. 3. Declaring and defining multiple variables in a single statementA comma separates each variable.
public class MainClass
{public static void main(String[] arg)
{
long a = 999999999L, b = 100000000L;int c = 0, d = 0;
8/9/2019 ComputerScienceReference-StatementControl
2/40
System.out.println(a);System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}4. 1. 4. Label a statement blockA statement and a statement block can be labeled.
Label names follow the same rule as Java identifiers and are terminated with a colon.
public class MainClass{
public static void main(String[] args)
{
int x = 0, y = 0;sectionA: x = y + 1;
}
}And, here is an example of labeling a block:
public class MainClass{
public static void main(String[] args)
{
start:{
// statements
}}
}Label statement can be referenced by the break and continue statements.
4. 1. 5. Spreading a single declaration over several linespublic class MainClass{
public static void main(String[] arg)
{int a = 0, // comment for a
b = 0, // comment for b
c = 0, // comment for cd = 0;
System.out.println(a);System.out.println(b);
System.out.println(c);
System.out.println(d);}
}
8/9/2019 ComputerScienceReference-StatementControl
3/40
4. 1. 6. How to write multiple assignments in a single statementpublic class MainClass
{
public static void main(String[] argv){
int a, b, c;a = b = c = 777;
System.out.println(a);
System.out.println(b);
System.out.println(c);}
}
Output:777
777
777
4. 1. 7. Combining both statements into oneclass Animal {
public Animal(String aType) {type = aType;
}
public String toString() {return "This is a " + type;
}
private String type;
}public class MainClass {
public static void main(String[] a) {
System.out.println(new Animal("a").getClass().getName()); // Output the// class name
}
}Output:
Animal
4. 1. 8. Statement Blocks
You can have a block of statements enclosed between braces.If the value of expression is true, all the statements enclosed in the block will be executed.
Without the braces, the code no longer has a statement block.
public class MainClass{
public static void main(String[] arg)
{int a = 0;
if (a == 0)
8/9/2019 ComputerScienceReference-StatementControl
4/40
{
System.out.println("in the block");System.out.println("in the block");
}
}
}
Output:in the block
in the block
4. 2. If Statement
4. 2. 1. The if statement syntax
4. 2. 2. Expression indentation for if statement4. 2. 3. Using braces makes your 'if' statement clearer
4. 2. 4. Multiple selections4. 2. 5. The if Statement in action4. 2. 6. The else Clause
4. 2. 7. Nested if Statements
4. 2. 8. Using && in if statement
4. 2. 9. Using || (or operator) in if statement
4. 2. 1. The if statement syntaxThe if statement is a conditional branch statement. The syntax of the if statement is either one of these two:
if (booleanExpression){
statement (s)}
or
if (booleanExpression)
{statement (s)
}
else{
statement (s)}
For example, in the following if statement, the if block will be executed if x is greater than 4.
public class MainClass{
public static void main(String[] args)
{int x = 9;
if (x > 4)
8/9/2019 ComputerScienceReference-StatementControl
5/40
{
// statements}
}
}
In the following example, the if block will be executed if a is greater than 3. Otherwise, the else block will be executed.
public class MainClass
{
public static void main(String[] args){
int a = 3;
if (a > 3)
{// statements
}
else{
// statements
}}
}
4. 2. 2. Expression indentation for if statementIf the expression is too long, you can use two units of indentation for subsequent lines.
public class MainClass{
public static void main(String[] args){
int numberOfLoginAttempts = 10;
int numberOfMinimumLoginAttempts = 12;
int numberOfMaximumLoginAttempts = 13;int y = 3;
if (numberOfLoginAttempts < numberOfMaximumLoginAttempts ||
numberOfMinimumLoginAttempts > y)
{y++;
}
}}
4. 2. 3. Using braces makes your 'if' statement clearerIf there is only one statement in an if or else block, the braces are optional.
public class MainClass {
public static void main(String[] args) {
8/9/2019 ComputerScienceReference-StatementControl
6/40
int a = 3;
if (a > 3)a++;
else
a = 3;
}
}
Consider the following example:
public class MainClass {
public static void main(String[] args) {
int a = 3, b = 1;
if (a > 0 || b < 5)
if (a > 2)
System.out.println("a > 2");
elseSystem.out.println("a < 2");
}
}
It is hard to tell which if statement the else statement is associated with.
Actually, An else statement is always associated with the immediately preceding if.
Using braces makes your code clearer.
public class MainClass {
public static void main(String[] args) {
int a = 3, b = 1;
if (a > 0 || b < 5) {
if (a > 2) {
System.out.println("a > 2");} else {
System.out.println("a < 2");
}}
}
}
4. 2. 4. Multiple selectionsIf there are multiple selections, you can also use if with a series of else statements.
if (booleanExpression1) {// statements
8/9/2019 ComputerScienceReference-StatementControl
7/40
} else if (booleanExpression2) {
// statements}
...
else {
// statements
}For example:
public class MainClass {
public static void main(String[] args) {int a = 0;
if (a == 1) {System.out.println("one");
} else if (a == 2) {
System.out.println("two");
} else if (a == 3) {System.out.println("three");
} else {
System.out.println("invalid");}
}
}
4. 2. 5. The if Statement in actionpublic class MainClass {
public static void main(String[] arg) {int a = 0;
if (a == 0) {System.out.println("a is 0");
}
}}
a is 0
4. 2. 6. The else Clausepublic class MainClass {
public static void main(String[] arg) {
int a = 0;
if (a == 0) {
8/9/2019 ComputerScienceReference-StatementControl
8/40
System.out.println("in the block");
System.out.println("in the block");} else {
System.out.println("a is not 0");
}
}
}in the block
in the block
4. 2. 7. Nested if Statementspublic class MainClass {
public static void main(String[] arg) {int a = 2;
if (a == 0) {
System.out.println("in the block");if (a == 2) {System.out.println("a is 0");
} else {
System.out.println("a is not 2");}
} else {System.out.println("a is not 0");
}
}
}a is not 0
4. 2. 8. Using && in if statementpublic class MainClass {
public static void main(String[] arg) {
int value = 8;
int count = 10;int limit = 11;
if (++value % 2 == 0 && ++count < limit) {System.out.println("here");
System.out.println(value);
System.out.println(count);
}System.out.println("there");
System.out.println(value);
System.out.println(count);
8/9/2019 ComputerScienceReference-StatementControl
9/40
}
}there
9
10
4. 2. 9. Using || (or operator) in if statementpublic class MainClass {
public static void main(String[] arg) {
int value = 8;int count = 10;
int limit = 11;
if (++value % 2 != 0 || ++count < limit) {
System.out.println("here");
System.out.println(value);System.out.println(count);}
System.out.println("there");
System.out.println(value);System.out.println(count);
}
}here
9
10
there9
10
4. 3. Switch Statement
4. 3. 1. The switch Statement4. 3. 2. The switch Statement: a demo
4. 3. 3. Execute the same statements for several different case labels
4. 3. 4. Free Flowing Switch Statement Example4. 3. 5. Nested Switch Statements Example
4. 3. 6. Switch statement with enum
4. 3. 1. The switch StatementAn alternative to a series of else if is the switch statement.
The switch statement allows you to choose a block of statements to run from a selection of code, based
on the return value of an expression.The expression used in the switch statement must return an int or an enumerated value.
The syntax of the switch statement is as follows.
switch (expression) {
8/9/2019 ComputerScienceReference-StatementControl
10/40
case value_1 :
statement (s);
break;
case value_2 :
statement (s);
break;.
.
.
case value_n :
statement (s);break;
default:
statement (s);}
Failure to add a break statement after a case will not generate a compile error but may have more
serious consequences because the statements on the next case will be executed.
Here is an example of the switch statement:
public class MainClass {
public static void main(String[] args) {
int i = 1;switch (i) {
case 1 :
System.out.println("One.");
break;case 2 :
System.out.println("Two.");
break;case 3 :
System.out.println("Three.");
break;default:
System.out.println("You did not enter a valid value.");
}}
}
4. 3. 2. The switch Statement: a demo
public class MainClass {
public static void main(String[] args) {int choice = 2;
switch (choice) {case 1:
8/9/2019 ComputerScienceReference-StatementControl
11/40
System.out.println("Choice 1 selected");
break;case 2:
System.out.println("Choice 2 selected");
break;
case 3:
System.out.println("Choice 3 selected");break;
default:System.out.println("Default");
break;
}}
}
Choice 2 selected
4. 3. 3. Execute the same statements for several different case labels
public class MainClass {
public static void main(String[] args) {
char yesNo = 'N';
switch(yesNo) {
case 'n': case 'N':System.out.println("No selected");
break;
case 'y': case 'Y':
System.out.println("Yes selected");break;
}
}}
No selected
4. 3. 4. Free Flowing Switch Statement Example
public class Main {
public static void main(String[] args) {
int i = 0;
switch (i) {
case 0:
System.out.println("i is 0");
case 1:System.out.println("i is 1");
case 2:
System.out.println("i is 2");default:
8/9/2019 ComputerScienceReference-StatementControl
12/40
System.out.println("Free flowing switch example!");
}}
}
/*
i is 0
i is 1i is 2
Free flowing switch example!*/
4. 3. 5. Nested Switch Statements Examplepublic class Main {
public static void main(String[] args) {int i = 0;
switch (i) {
case 0:
int j = 1;switch (j) {
case 0:
System.out.println("i is 0, j is 0");break;
case 1:
System.out.println("i is 0, j is 1");break;
default:
System.out.println("nested default case!!");
}break;
default:
System.out.println("No matching case found!!");}
}
}//i is 0, j is 1
4. 3. 6. Switch statement with enumpublic class MainClass {
enum Choice { Choice1, Choice2, Choice3 }
public static void main(String[] args) {
Choice ch = Choice.Choice1;
switch(ch) {
case Choice1:System.out.println("Choice1 selected");
break;
case Choice2:System.out.println("Choice2 selected");
8/9/2019 ComputerScienceReference-StatementControl
13/40
break;
case Choice3:System.out.println("Choice3 selected");
break;
}
}
}Choice1 selected
4. 4. While Loop
4. 4. 1. The while Statement
4. 4. 2. Using the while loop to calculate sum4. 4. 3. While loop with double value
4. 4. 4. Java's 'labeled while' loop
4. 4. 1. The while Statement
One way to create a loop is by using the while statement.
Another way is to use the for statementThe while statement has the following syntax.
while (booleanExpression) {
statement (s)}
statement(s) will be executed as long as booleanExpression evaluates to true.
If there is only a single statement inside the braces, you may omit the braces.For clarity, you should always use braces even when there is only one statement.
As an example of the while statement, the following code prints integer numbers that are less than
three.
public class MainClass {
public static void main(String[] args) {
int i = 0;
while (i < 3) {
System.out.println(i);i++;
}
}
}
To produce three beeps with an interval of 500 milliseconds, use this code:
8/9/2019 ComputerScienceReference-StatementControl
14/40
public class MainClass {
public static void main(String[] args) {
int j = 0;
while (j < 3) {
java.awt.Toolkit.getDefaultToolkit().beep();
try {Thread.currentThread().sleep(500);
} catch (Exception e) {}
j++;
}}
}Sometimes, you use an expression that always evaluates to true (such as the boolean literal true) but
relies on the break statement to escape from the loop.
public class MainClass {
public static void main(String[] args) {
int k = 0;while (true) {
System.out.println(k);
k++;if (k > 2) {
break;
}
}}
}
4. 4. 2. Using the while loop to calculate sumpublic class MainClass {
public static void main(String[] args) {
int limit = 20;int sum = 0;
int i = 1;
while (i
8/9/2019 ComputerScienceReference-StatementControl
15/40
4. 4. 3. While loop with double valuepublic class MainClass {
public static void main(String[] args) {
double r = 0;
while(r < 0.99d) {
r = Math.random();System.out.println(r);
}}
}
0.43772789973053870.2688654455422754
0.36392537297385574
0.152544135113610420.6688621030424611
0.143156733550304
0.3867695752401421
0.63484960311260750.8262243996358971
0.057290108917235516
4. 4. 4. Java's 'labeled while' loop
public class MainClass {
public static void main(String[] args) {int i = 0;
outer: while (true) {
System.out.println("Outer while loop");
while (true) {i++;
System.out.println("i = " + i);
if (i == 1) {System.out.println("continue");
continue;
}if (i == 3) {
System.out.println("continue outer");
continue outer;}
if (i == 5) {
System.out.println("break");
break;}
if (i == 7) {
System.out.println("break outer");break outer;
}
}}
8/9/2019 ComputerScienceReference-StatementControl
16/40
}
}Outer while loop
i = 1
continue
i = 2
i = 3continue outer
Outer while loopi = 4
i = 5
breakOuter while loop
i = 6
i = 7break outer
4. 5. Do While Loop4. 5. 1. The do-while Statement
4. 5. 2. The do while loop in action
4. 5. 1. The do-while Statement
The do-while statement is like the while statement, except that the associated block always gets
executed at least once.
Its syntax is as follows:
do {statement (s)
} while (booleanExpression);
Just like the while statement, you can omit the braces if there is only one statement within them.However, always use braces for the sake of clarity.
public class MainClass {
public static void main(String[] args) {
int i = 0;
do {System.out.println(i);
i++;
} while (i < 3);}
}This prints the following to the console:
8/9/2019 ComputerScienceReference-StatementControl
17/40
01
2
The following do-while demonstrates that at least the code in the do block will be executed once even
though the initial value of j used to test the expression j < 3 evaluates to false.
public class MainClass {
public static void main(String[] args) {
int j = 4;
do {System.out.println(j);
j++;
} while (j < 3);}
}
This prints the following on the console.
4
4. 5. 2. The do while loop in action
do {
// statements} while (expression);
public class MainClass {
public static void main(String[] args) {
int limit = 20;int sum = 0;
int i = 1;
do {
sum += i;
i++;} while (i
8/9/2019 ComputerScienceReference-StatementControl
18/40
4. 6. 2. For statement in detail
4. 6. 3. A loop allows you to execute a statement or block of statements repeatedly4. 6. 4. The numerical for loop
4. 6. 5. Infinite For loop Example
4. 6. 6. initialization_expression: define two variables in for loop
4. 6. 7. Declare multiple variables in for loop
4. 6. 8. Multiple expressions in for loops4. 6. 9. To omit any or all of the elements in 'for' loop: but you must include the semicolons
4. 6. 10. Keeping the middle element only in for loop4. 6. 11. Using the Floating-Point Values as the control value in a for loop
4. 6. 12. Nested for Loop
4. 6. 13. Java's 'labeled for' loop4. 6. 14. Print out a Diamond
4. 6. 1. The for Statement
The for statement is like the while statement, i.e. you use it to create loop. The for statement has
following syntax:
for ( init ; booleanExpression ; update ) {
statement (s)
}init is an initialization that will be performed before the first iteration.
booleanExpression is a boolean expression which will cause the execution of statement(s) if it
evaluates to true.update is a statement that will be executed after the execution of the statement block.
init, expression, and update are optional.
The for statement will stop only if one of the following conditions is met:
booleanExpression evaluates to false
A break or continue statement is executed
A runtime error occurs.
4. 6. 2. For statement in detailIt is common to declare a variable and assign a value to it in the initialization part. The variable
declared will be visible to the expression and update parts as well as to the statement block.
For example, the following for statement loops five times and each time prints the value of i. Note that
the variable i is not visible anywhere else since it is declared within the for loop.
public class MainClass {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {System.out.println(i + " ");
}
}}
8/9/2019 ComputerScienceReference-StatementControl
19/40
The initialization part of the for statement is optional.
public class MainClass {
public static void main(String[] args) {
int j = 0;
for (; j < 3; j++) {System.out.println(j);
}// j is visible here
}
}
The update statement is optional.
public class MainClass {
public static void main(String[] args) {
int k = 0;for (; k < 3;) {
System.out.println(k);
k++;}
}
}
You can even omit the booleanExpression part.
public class MainClass {
public static void main(String[] args) {
int m = 0;for (;;) {
System.out.println(m);
m++;if (m > 4) {
break;
}}
}
}If you compare for and while, you'll see that you can always replace the while statement with for. This
is to say that
while (expression) {
...
}
8/9/2019 ComputerScienceReference-StatementControl
20/40
can always be written as
for ( ; expression; ) {
...
}
4. 6. 3. A loop allows you to execute a statement or block of statements repeatedlypublic class MainClass {
public static void main(String[] args) {
for (int i = 0; i < 8; i++) {System.out.println("Hi.");
}
}}
Hi.
Hi.
Hi.Hi.
Hi.
Hi.Hi.
Hi.
4. 6. 4. The numerical for loop
for (initialization_expression ; loop_condition ; increment_expression) {
// statements}
public class MainClass {
public static void main(String[] args) {int limit = 20; // Sum from 1 to this value
int sum = 0; // Accumulate sum in this variable
for (int i = 1; i
8/9/2019 ComputerScienceReference-StatementControl
21/40
System.out.println("Hello");
break;}
}
}
//Hello
4. 6. 6. initialization_expression: define two variables in for looppublic class MainClass {
public static void main(String[] arg) {int limit = 10;
int sum = 0;
for (int i = 1, j = 0; i
8/9/2019 ComputerScienceReference-StatementControl
22/40
i = 2 j= -2
i = 3 j= -3i = 4 j= -4
*/
4. 6. 9. To omit any or all of the elements in 'for' loop: but you must include the semicolonspublic class MainClass {
public static void main(String[] arg) {
int limit = 10;
int sum = 0;
for (int i = 1; i
8/9/2019 ComputerScienceReference-StatementControl
23/40
radius = 1.0area = 3.141592653589793
radius = 1.2area = 4.523893421169302radius = 1.4area = 6.157521601035994
radius = 1.5999999999999999area = 8.04247719318987
radius = 1.7999999999999998area = 10.178760197630927
radius = 1.9999999999999998area = 12.566370614359169
4. 6. 12. Nested for Looppublic class MainClass {
public static void main(String[] args) {
long limit = 20L;long factorial = 1L;
for (long i = 1L; i
8/9/2019 ComputerScienceReference-StatementControl
24/40
inner: for (; i < 10; i++) {
System.out.println("i = " + i);if (i == 2) {
System.out.println("continue");
continue;
}
if (i == 3) {System.out.println("break");
i++;break;
}
if (i == 7) {System.out.println("continue outer");
i++;
continue outer;}
if (i == 8) {
System.out.println("break outer");
break outer;}
for (int k = 0; k < 5; k++) {
if (k == 3) {System.out.println("continue inner");
continue inner;
}}
}
}
}}
i = 0
continue inneri = 1
continue inner
i = 2continue
i = 3
breaki = 4
continue inner
i = 5
continue inneri = 6
continue inner
i = 7continue outer
i = 8
break outer
8/9/2019 ComputerScienceReference-StatementControl
25/40
4. 6. 14. Print out a Diamondclass Diamond {
public static void main(String[] args) {
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)System.out.print("*");
System.out.print("\n");}
for (int i = 7; i > 0; i -= 2) {for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)System.out.print("*");
System.out.print("\n");}
}
}/*
*
***
************
*********
************
***
**/
4. 7. For Each Loop
4. 7. 1. The For-Each Version of the for Loop
4. 7. 2. The for-each loop is essentially read-only
4. 7. 3. The for each loop for an enum data type4. 7. 4. Using the For-Each Loop with Collections: ArrayList
4. 7. 5. Use a for-each style for loop
4. 7. 6. Using 'for each' to loop through array4. 7. 7. Iterating over Multidimensional Arrays: Use for-each style for on a two-dimensional
array
4. 7. 8. Using break with a for-each-style for
8/9/2019 ComputerScienceReference-StatementControl
26/40
4. 7. 1. The For-Each Version of the for Loop
The general form of the for-each version of the for is shown here:
for(type itr-var : iterableObj) statement-block
The object referred to by iterableObj must be an array or an object that implements the new Iterable
interface.
4. 7. 2. The for-each loop is essentially read-only
public class MainClass {public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x : nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums}
System.out.println();
for(int x : nums)
System.out.print(x + " ");
System.out.println();
}
}1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
4. 7. 3. The for each loop for an enum data typefor (type identifier : iterable_expression) {
// statements
}public class MainClass {
enum Season {
spring, summer, fall, winter}
public static void main(String[] args) {for (Season season : Season.values()) {
System.out.println(" The season is now " + season);
}
}}
The season is now spring
The season is now summerThe season is now fall
The season is now winter
4. 7. 4. Using the For-Each Loop with Collections: ArrayList
8/9/2019 ComputerScienceReference-StatementControl
27/40
For-Each Loop can be used to any object that implements the Iterable interface. This includes all
collections defined by the Collections Framework,
import java.util.ArrayList;
public class MainClass {
public static void main(String args[]) {
ArrayList list = new ArrayList();
list.add(10.14);
list.add(20.22);list.add(30.78);
list.add(40.46);
double sum = 0.0;
for(double itr : list)
sum = sum + itr;
System.out.println(sum);
}
}101.6
4. 7. 5. Use a for-each style for looppublic class MainClass {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}}
Value is: 1
Value is: 2
Value is: 3Value is: 4
Value is: 5
Value is: 6Value is: 7
Value is: 8
Value is: 9Value is: 10
8/9/2019 ComputerScienceReference-StatementControl
28/40
Summation: 55
4. 7. 6. Using 'for each' to loop through array
public class MainClass {
public static void main(String[] arg) {
char[] vowels = { 'a', 'e', 'i', 'o', 'u'};
for(char ch: vowels){System.out.println(ch);
}
}}
a
ei
o
u
4. 7. 7. Iterating over Multidimensional Arrays: Use for-each style for on a two-dimensional array
public class MainClass {public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
// give nums some values
for (int i = 0; i < 3; i++)
for (int j = 0; j < 5; j++)nums[i][j] = (i + 1) * (j + 1);
// use for-each for to display and sum the valuesfor (int x[] : nums) {
for (int y : x) {
System.out.println("Value is: " + y);sum += y;
}
}System.out.println("Summation: " + sum);
}
}
4. 7. 8. Using break with a for-each-style for
public class MainClass {
public static void main(String args[]) {int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Use for to display and sum the values.
8/9/2019 ComputerScienceReference-StatementControl
29/40
for (int x : nums) {
System.out.println("Value is: " + x);sum += x;
if (x == 5){
break; // stop the loop when 5 is obtained
}
}System.out.println("Summation of first 5 elements: " + sum);
}}
Value is: 1
Value is: 2Value is: 3
Value is: 4
Value is: 5Summation of first 5 elements: 15
4. 8. Break Statement
4. 8. 1. The break Statement4. 8. 2. Using the break Statement in a Loop: break out from a loop
4. 8. 3. Breaking Indefinite Loops
4. 8. 4. Labelled breaks breaks out of several levels of nested loops inside a pair of curly braces.
4. 8. 5. The Labeled break Statemen
4. 8. 1. The break Statement
The break statement is used to break from an enclosing do, while, for, or switch statement.
It is a compile error to use break anywhere else.
'break' breaks the loop without executing the rest of the statements in the block.For example, consider the following code
public class MainClass {
public static void main(String[] args) {
int i = 0;while (true) {
System.out.println(i);
i++;if (i > 3) {
break;
}
}}
}The result is
01
8/9/2019 ComputerScienceReference-StatementControl
30/40
2
3
4. 8. 2. Using the break Statement in a Loop: break out from a loop
public class MainClass {
public static void main(String[] args) {
int count = 50;
for (int j = 1; j < count; j++) {if (count % j == 0) {
System.out.println("Breaking!!");
break;}
}
}}
Breaking!!
4. 8. 3. Breaking Indefinite Loopspublic class MainClass {
public static void main(String[] args) {
OuterLoop: for (int i = 2;; i++) {
for (int j = 2; j < i; j++) {
if (i % j == 0) {continue OuterLoop;
}
}
System.out.println(i);
if (i == 107) {
break;}
}
}}
2
35
7
11
1317
19
2329
31
3741
8/9/2019 ComputerScienceReference-StatementControl
31/40
8/9/2019 ComputerScienceReference-StatementControl
32/40
}
System.out.println(i);if (i == 37) {
break OuterLoop;
}
}
}}
23
5
711
13
1719
23
29
3137
4. 9. Continue Statement4. 9. 1. The continue Statement
4. 9. 2. The continue statement: skips all or part of a loop iteration
4. 9. 3. The Labeled continue statement4. 9. 4. Calculating Primes: using continue statement and label
4. 9. 1. The continue Statement
The continue statement stops the execution of the current iteration and causes control to begin with thenext iteration.
For example, the following code prints the number 0 to 9, except 5.
public class MainClass {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 5) {continue;
}
System.out.println(i);
}}
}
4. 9. 2. The continue statement: skips all or part of a loop iteration
public class MainClass {
8/9/2019 ComputerScienceReference-StatementControl
33/40
public static void main(String[] arg) {
int limit = 10;int sum = 0;
for (int i = 1; i
8/9/2019 ComputerScienceReference-StatementControl
34/40
4. 9. 4. Calculating Primes: using continue statement and label
continue may be followed by a label to identify which enclosing loop to continue to.
public class MainClass {
public static void main(String[] args) {
int nValues = 50;
OuterLoop: for (int i = 2; i
8/9/2019 ComputerScienceReference-StatementControl
35/40
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { //System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
4. 10. 2. Handle an exception and move on.
import java.util.Random;
public class MainClass {
public static void main(String args[]) {
int a = 0, b = 0, c = 0;Random r = new Random();
for (int i = 0; i < 32000; i++) {
try {b = r.nextInt();
c = r.nextInt();
a = 12345 / (b / c);} catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue}
System.out.println("a: " + a);
}
}}
4. 10. 3. Demonstrate multiple catch statements.class MultiCatch {
public static void main(String args[]) {
try {int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;int c[] = { 1 };
c[42] = 99;
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}System.out.println("After try/catch blocks.");
}
}
8/9/2019 ComputerScienceReference-StatementControl
36/40
4. 10. 4. Catch different Exception types
class MyException extends Exception {MyException() {
super("My Exception");
}
}
class YourException extends Exception {
YourException() {super("Your Exception");
}
}
class LostException {
public static void main(String[] args) {try {
someMethod1();
} catch (MyException e) {
System.out.println(e.getMessage());} catch (YourException e) {
System.out.println(e.getMessage());
}}
static void someMethod1() throws MyException, YourException {try {
someMethod2();
} finally {
throw new MyException();}
}
static void someMethod2() throws YourException {
throw new YourException();
}}
4. 10. 5. An example of nested try statements.class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try {if (a == 1)
8/9/2019 ComputerScienceReference-StatementControl
37/40
a = a / (a - a); // division by zero
if (a == 2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch (ArrayIndexOutOfBoundsException e) {System.out.println("Array index out-of-bounds: " + e);
}
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);}
}
}
4. 10. 6. Try statements can be implicitly nested via calls to methods
class MethNestTry {
static void nesttry(int a) {try {
if (a == 1)
a = a / (a - a);if (a == 2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}}
public static void main(String args[]) {try {
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
nesttry(a);
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}}
}
4. 11. throw
8/9/2019 ComputerScienceReference-StatementControl
38/40
4. 11. 1. Demonstrate throw.
4. 11. 2. Change Exception type and rethrow
4. 11. 1. Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {throw new NullPointerException("demo");
} catch (NullPointerException e) {System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}}
public static void main(String args[]) {try {
demoproc();
} catch (NullPointerException e) {
System.out.println("Recaught: " + e);}
}
}
4. 11. 2. Change Exception type and rethrow
class MyException extends Exception {MyException() {
super("My Exception");
}
}
class YourException extends Exception {
YourException() {super("Your Exception");
}
}
class ChainDemo {
public static void main(String[] args) {try {
someMethod1();
} catch (MyException e) {
e.printStackTrace();}
}
static void someMethod1() throws MyException {
try {
someMethod2();} catch (YourException e) {
8/9/2019 ComputerScienceReference-StatementControl
39/40
System.out.println(e.getMessage());
MyException e2 = new MyException();e2.initCause(e);
throw e2;
}
}
static void someMethod2() throws YourException {
throw new YourException();}
}
4. 12. finally4. 12. 1. Demonstrate finally.
4. 12. 1. Demonstrate finally.
class FinallyDemo {static void procA() {
try {
System.out.println("inside procA");throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");}
}
static void procB() {try {
System.out.println("inside procB");
return;} finally {
System.out.println("procB's finally");
}}
static void procC() {try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");}
}
public static void main(String args[]) {
try {
procA();} catch (Exception e) {
8/9/2019 ComputerScienceReference-StatementControl
40/40
System.out.println("Exception caught");
}procB();
procC();
}
}
4. 13. throws signature
4. 13. 1. throws Exception from method
4. 13. 1. throws Exception from method
class ThrowsDemo {static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");}
public static void main(String args[]) {
try {throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);}
}
}