Académique Documents
Professionnel Documents
Culture Documents
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. 2. Expressions
Some expressions can be made statements by terminating them with a semicolon. For example, x++ is an expression. However, this is a stateme
x++;
Statements can be grouped in a block. A block is a sequence of the following programming elements within braces:
1. statements
2. local class declarations
3. local variable declaration statements
int c = 0, d = 0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
999999999
100000000
0
0
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
a = b = c = 777;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
777
777
777
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
}
}
Animal
4. 1. 8. Statement Blocks
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
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 {
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 {
}
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 {
If there is only one statement in an if or else block, the braces are optional.
public class MainClass {
if (a > 0 || b < 5)
if (a > 2)
System.out.println("a > 2");
else
System.out.println("a < 2");
}
}
1. It is hard to tell which if statement the else statement is associated with.
2. Actually, An else statement is always associated with the immediately preceding if.
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 {
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
if (a == 0) {
System.out.println("a is 0");
}
}
}
a is 0
in the block
in the block
4. 2. 7. Nested if Statements
} else {
System.out.println("a is not 0");
}
}
}
a is not 0
there
9
10
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 o
the next case will be executed.
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
switch(yesNo) {
case 'n': case 'N':
System.out.println("No selected");
break;
case 'y': case 'Y':
System.out.println("Yes selected");
break;
}
}
}
No selected
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!
*/
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
As an example of the while statement, the following code prints integer numbers that are less than three.
public class MainClass {
To produce three beeps with an interval of 500 milliseconds, use this code:
public class MainClass {
}
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
loop.
public class MainClass {
sum = 210
0.4377278997305387
0.2688654455422754
0.36392537297385574
0.15254413511361042
0.6688621030424611
0.143156733550304
0.3867695752401421
0.6348496031126075
0.8262243996358971
0.057290108917235516
0.48887104413122007
0.9181002018325309
0.03580026338719999
0.6915245271034702
0.06281957479185263
0.7484170566879976
0.08309381253696246
0.7708638307798187
0.6586973690207539
0.3606321940413979
0.17404632324149583
0.1007512703731156
0.7971297767971545
0.4461084890266951
0.8627269068871244
0.04984737498714209
0.2597921665157922
0.5410470601800582
0.5779541886682865
0.1847556794086489
0.32127067165147705
0.12266607697656651
0.62729812639505
0.12191275953517977
0.72308829958122
0.5766115831015479
0.03444891261877858
0.3034596140603594
0.058872682884219985
0.85618745813345
0.07472991871327217
0.32676415639620604
0.6390549075075913
0.09246846051500635
0.9135703200463736
0.661365290176903
0.834153688687532
0.6340862529502882
0.3240420706550172
0.07246065490188025
0.35761285323105796
0.9964556875646731
The do-while statement is like the while statement, except that the associated block always gets executed at least once.
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 clar
public class MainClass {
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 th
expression j < 3 evaluates to false.
public class MainClass {
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);
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
To omit any or all of the elements in 'for' loop: but you must include the
4. 6. 9.
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
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)
}
The for statement will stop only if one of the following conditions is met:
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 up
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 {
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) {
...
}
Hi.
Hi.
Hi.
Hi.
Hi.
Hi.
Hi.
Hi.
sum = 210
330
4. 6. 9. To omit any or all of the elements in 'for' loop: but you must include the semicolons
55
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
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
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
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(" ");
System.out.print("\n");
}
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
Iterating over Multidimensional Arrays: Use for-each style for on a two-
4. 7. 7.
dimensional array
4. 7. 8. Using break with a for-each-style for
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.
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
For-Each Loop can be used to any object that implements the Iterable interface. This includes all collections defined by the Collections Framew
import java.util.ArrayList;
list.add(10.14);
list.add(20.22);
list.add(30.78);
list.add(40.46);
}
}
101.6
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
a
e
i
o
u
4. 7. 7. Iterating over Multidimensional Arrays: Use for-each style for on a two-dimensional array
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90
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
Labelled breaks breaks out of several levels of nested loops inside a pair of
4. 8. 4.
curly braces.
4. 8. 5. The Labeled break Statement
1. The break statement is used to break from an enclosing do, while, for, or switch statement.
2. It is a compile error to use break anywhere else.
3. 'break' breaks the loop without executing the rest of the statements in the block.
The result is
0
1
2
3
4. 8. 2. Using the break Statement in a Loop: break out from a loop
Breaking!!
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.
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
The continue statement stops the execution of the current iteration and causes control to begin with the next iteration.
37
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
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;
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
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.");
}
}
import java.util.Random;
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.");
}
}
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();
}
}
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / 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);
}
}
}
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);
}
}
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
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch (NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
class ChainDemo {
public static void main(String[] args) {
try {
someMethod1();
} catch (MyException e) {
e.printStackTrace();
}
}
class FinallyDemo {
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}