Вы находитесь на странице: 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. Statement
4. 1. 1. An Overview of Java Statements
4. 1. 2. Expressions
4. 1. 3. Declaring and defining multiple variables in a single statement
4. 1. 4. Label a statement block
4. 1. 5. Spreading a single declaration over several lines
4. 1. 6. How to write multiple assignments in a single statement
4. 1. 7. Combining both statements into one
4. 1. 8. Statement Blocks

4. 1. 1. An Overview of Java Statements


In 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. Expressions
Some 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 declarations
local variable declaration statements

4. 1. 3. Declaring and defining multiple variables in a single statement


A comma separates each variable.

public class MainClass


{
public static void main(String[] arg)
{
long a = 999999999L, b = 100000000L;
int c = 0, d = 0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
4. 1. 4. Label a statement block
A 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 lines


public class MainClass
{

public static void main(String[] arg)


{
int a = 0, // comment for a
b = 0, // comment for b
c = 0, // comment for c
d = 0;

System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
4. 1. 6. How to write multiple assignments in a single statement
public 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 one


class 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)
{
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 statement
4. 2. 3. Using braces makes your 'if' statement clearer
4. 2. 4. Multiple selections
4. 2. 5. The if Statement in action
4. 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 syntax


The 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)
{
// 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 statement


If 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 clearer


If there is only one statement in an if or else block, the braces are optional.

public class MainClass {

public static void main(String[] args) {


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");
else
System.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 selections
If there are multiple selections, you can also use if with a series of else statements.

if (booleanExpression1) {
// statements
} 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 action


public 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 Clause


public class MainClass {

public static void main(String[] arg) {


int a = 0;
if (a == 0) {
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 Statements
public 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 statement


public 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);
}
}
there
9
10

4. 2. 9. Using || (or operator) in if statement


public 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
there
9
10

4. 3. Switch Statement
4. 3. 1. The switch Statement
4. 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 Example
4. 3. 5. Nested Switch Statements Example
4. 3. 6. Switch statement with enum

4. 3. 1. The switch Statement


An 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) {
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:
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:
System.out.println("Free flowing switch example!");
}
}
}
/*
i is 0
i is 1
i is 2
Free flowing switch example!
*/

4. 3. 5. Nested Switch Statements Example


public 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 enum


public 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");
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 sum
4. 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 statement
The 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:
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 sum


public class MainClass {
public static void main(String[] args) {
int limit = 20;
int sum = 0;
int i = 1;

while (i <= limit) {


sum += i++;
}
System.out.println("sum = " + sum);
}
}
sum = 210
4. 4. 3. While loop with double value
public class MainClass {
public static void main(String[] args) {
double r = 0;
while(r < 0.99d) {
r = Math.random();
System.out.println(r);
}
}
}
0.4377278997305387
0.2688654455422754
0.36392537297385574
0.15254413511361042
0.6688621030424611
0.143156733550304
0.3867695752401421
0.6348496031126075
0.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;
}
}
}
}
}
Outer while loop
i=1
continue
i=2
i=3
continue outer
Outer while loop
i=4
i=5
break
Outer while loop
i=6
i=7
break outer

4. 5. Do While Loop
4. 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:
0
1
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. 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 <= limit);

System.out.println("sum = " + sum);


}
}
sum = 210

4. 6. For Loop
4. 6. 1. The for Statement
4. 6. 2. For statement in detail
4. 6. 3. A loop allows you to execute a statement or block of statements repeatedly
4. 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 loops
4. 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 loop
4. 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' loop
4. 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 detail


It 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 + " ");
}
}
}
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) {
...
}
can always be written as

for ( ; expression; ) {
...
}

4. 6. 3. A loop allows you to execute a statement or block of statements repeatedly


public 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 <= limit; i++) {


sum = sum + i;
}
System.out.println("sum = " + sum);
}
}
sum = 210

4. 6. 5. Infinite For loop Example


public class Main {

public static void main(String[] args) {


for (;;) {
System.out.println("Hello");
break;
}
}
}
//Hello

4. 6. 6. initialization_expression: define two variables in for loop


public class MainClass {

public static void main(String[] arg) {


int limit = 10;
int sum = 0;
for (int i = 1, j = 0; i <= limit; i++, j++) {
sum += i * j;
}
System.out.println(sum);
}
}
330

public class Main {


public static void main(String[] args) {
for (int i = 0, j = 1, k = 2; i < 5; i++){
System.out.println("I : " + i + ",j : " + j + ", k : " + k);
}
}
}
/*
I : 0,j : 1, k : 2
I : 1,j : 1, k : 2
I : 2,j : 1, k : 2
I : 3,j : 1, k : 2
I : 4,j : 1, k : 2
*/

4. 6. 8. Multiple expressions in for loops


public class Main {
public static void main(String[] args) {
for (int i = 0, j = 0; i < 5; i++, j--)
System.out.println("i = " + i + " j= " + j);
}
}
/*
i = 0 j= 0
i = 1 j= -1
i = 2 j= -2
i = 3 j= -3
i = 4 j= -4
*/

4. 6. 9. To omit any or all of the elements in 'for' loop: but you must include the semicolons
public class MainClass {

public static void main(String[] arg) {


int limit = 10;
int sum = 0;

for (int i = 1; i <= limit;) {


sum += i++;
}
System.out.println(sum);
}
}
55

4. 6. 10. Keeping the middle element only in for loop


public class MainClass {

public static void main(String[] arg) {


int limit = 10;
int sum = 0;

int i = 1;
for (; i <= limit;) {
sum += i++;
}
System.out.println(sum);
}

}
55

4. 6. 11. Using the Floating-Point Values as the control value in a for loop
public class MainClass {

public static void main(String[] arg) {


for (double radius = 1.0; radius <= 2.0; radius += 0.2) {
System.out.println("radius = " + radius + "area = " + Math.PI * radius * radius);
}
}

}
radius = 1.0area = 3.141592653589793
radius = 1.2area = 4.523893421169302
radius = 1.4area = 6.157521601035994
radius = 1.5999999999999999area = 8.04247719318987
radius = 1.7999999999999998area = 10.178760197630927
radius = 1.9999999999999998area = 12.566370614359169

4. 6. 12. Nested for Loop


public class MainClass {
public static void main(String[] args) {
long limit = 20L;
long factorial = 1L;

for (long i = 1L; i <= limit; i++) {


factorial = 1L;

for (long factor = 2; factor <= i; factor++) {


factorial *= factor;
}
System.out.println(i + "! is " + factorial);
}
}
}
1! is 1
2! is 2
3! is 6
4! is 24
5! is 120
6! is 720
7! is 5040
8! is 40320
9! is 362880
10! is 3628800
11! is 39916800
12! is 479001600
13! is 6227020800
14! is 87178291200
15! is 1307674368000
16! is 20922789888000
17! is 355687428096000
18! is 6402373705728000
19! is 121645100408832000
20! is 2432902008176640000

public class MainClass {


public static void main(String[] args) {
int i = 0;
outer: for (; true;) {
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 inner
i=1
continue inner
i=2
continue
i=3
break
i=4
continue inner
i=5
continue inner
i=6
continue inner
i=7
continue outer
i=8
break outer
4. 6. 14. Print out a Diamond
class 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 type
4. 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 array
4. 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
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 type


for (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 summer
The season is now fall
The season is now winter

4. 7. 4. Using the For-Each Loop with Collections: ArrayList


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<Double> list = new ArrayList<Double>();

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 loop


public 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: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
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
e
i
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 values


for (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.


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: 2
Value is: 3
Value is: 4
Value is: 5
Summation of first 5 elements: 15

4. 8. Break Statement
4. 8. 1. The break Statement
4. 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

0
1
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 Loops


public 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
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107

4. 8. 4. Labelled breaks breaks out of several levels of nested loops inside a pair of curly braces.
public class Main {
public static void main(String args[]) {

int len = 100;


int key = 50;
int k = 0;
out: {
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (i == key) {
break out;
}
k += 1;
}
}
}
System.out.println(k);
}
}

4. 8. 5. The Labeled break Statement


The break statement can be followed by a label.
The presence of a label will transfer control to the start of the code identified by the label.
For example, consider this code.
public 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 == 37) {
break OuterLoop;
}
}
}
}
2
3
5
7
11
13
17
19
23
29
31
37

4. 9. Continue Statement
4. 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 statement
4. 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 the
next 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 {
public static void main(String[] arg) {
int limit = 10;
int sum = 0;
for (int i = 1; i <= limit; i++) {
if (i % 3 == 0) {
continue;
}
sum += i;
}
System.out.println(sum);
}

}
37

4. 9. 3. The Labeled continue statement


public class MainClass {
public static void main(String[] args) {
int limit = 20;
int factorial = 1;

OuterLoop: for (int i = 1; i <= limit; i++) {


factorial = 1;
for (int j = 2; j <= i; j++) {
if (i > 10 && i % 2 == 1) {
continue OuterLoop;
}
factorial *= j;
}
System.out.println(i + "! is " + factorial);
}
}
}
1! is 1
2! is 2
3! is 6
4! is 24
5! is 120
6! is 720
7! is 5040
8! is 40320
9! is 362880
10! is 3628800
12! is 479001600
14! is 1278945280
16! is 2004189184
18! is -898433024
20! is -2102132736
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 <= nValues; i++) {


for (int j = 2; j < i; j++) {
if (i % j == 0) {
continue OuterLoop;
}
}
System.out.println(i);
}
}
}
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

4. 10. try catch


4. 10. 1. catch divide-by-zero error
4. 10. 2. Handle an exception and move on.
4. 10. 3. Demonstrate multiple catch statements.
4. 10. 4. Catch different Exception types
4. 10. 5. An example of nested try statements.
4. 10. 6. Try statements can be implicitly nested via calls to methods

4. 10. 1. catch divide-by-zero error


public class MainClass {
public static void main(String args[]) {
int d, a;

try {
d = 0;
a = 42 / d;
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.");
}
}
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)
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
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) {
System.out.println(e.getMessage());
MyException e2 = new MyException();
e2.initCause(e);
throw e2;
}
}

static void someMethod2() throws YourException {


throw new YourException();
}
}

4. 12. finally
4. 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) {
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);
}
}
}

Вам также может понравиться