49
 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 )

Computer Science Reference Java Statements

Embed Size (px)

Citation preview

Page 1: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 1/49

 

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 )

Page 2: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 2/49

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

1.  In programming, a statement is an instruction to do something.

2.  It controls the sequence of execution of a program.

3.  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 isx++;

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

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;

Page 3: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 3/49

 System.out.println(a);System.out.println(b);System.out.println(c);System.out.println(d);}

}

99999999910000000000

4. 1. 4. Label a statement block

1.  A statement and a statement block can be labeled.2.  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 

Page 4: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 4/49

  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); 

}

777777777

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 } 

}

Animal

Page 5: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 5/49

 

4. 1. 8. Statement Blocks

1.  You can have a block of statements enclosed between braces.

2.  If the value of expression is true, all the statements enclosed in the block will be executed.

3.  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");

}}

}

in the blockin the block

Page 6: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 6/49

 

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 }

}

}

Page 7: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 7/49

 

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");

}

}

Page 8: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 8/49

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.

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");}

}

}

Page 9: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 9/49

 

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 blockin 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 { 

Page 10: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 10/49

  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); 

} }

there910

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); 

} }

Page 11: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 11/49

 

here910there910

Page 12: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 12/49

 

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

1.  An alternative to a series of else if is the switch statement.

2.  The switch statement allows you to choose a block of statements to run from a selection of code, based on the return value of

3.  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 sta

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;

Page 13: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 13/49

  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; 

} } 

}

Page 14: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 14/49

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!!"); 

} } 

Page 15: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 15/49

} //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

Page 16: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 16/49

 

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

1.  One way to create a loop is by using the while statement.

2.  Another way is to use the for statement

The while statement has the following syntax.

while (booleanExpression) {statement (s)

}

1.  statement(s) will be executed as long as booleanExpression evaluates to true.

2.  If there is only a single statement inside the braces, you may omit the braces.

3.  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++;

}}

}

Page 17: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 17/49

 

Sometimes, you use an expression that always evaluates to true (such as the boolean literal true) but relies on the break statement to es

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.43772789973053870.26886544554227540.36392537297385574

Page 18: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 18/49

0.152544135113610420.66886210304246110.1431567335503040.38676957524014210.63484960311260750.82622439963589710.0572901089172355160.488871044131220070.91810020183253090.035800263387199990.69152452710347020.062819574791852630.74841705668799760.083093812536962460.77086383077981870.65869736902075390.36063219404139790.174046323241495830.10075127037311560.79712977679715450.44610848902669510.86272690688712440.04984737498714209

0.25979216651579220.54104706018005820.57795418866828650.18475567940864890.321270671651477050.122666076976566510.627298126395050.121912759535179770.723088299581220.57661158310154790.034448912618778580.30345961406035940.0588726828842199850.856187458133450.074729918713272170.326764156396206040.63905490750759130.092468460515006350.91357032004637360.6613652901769030.8341536886875320.63408625295028820.32404207065501720.072460654901880250.357612853231057960.9964556875646731

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"); 

Page 19: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 19/49

  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 loopi = 1continuei = 2i = 3continue outerOuter while loopi = 4i = 5breakOuter while loopi = 6

i = 7break outer

Page 20: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 20/49

 

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 s

 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:

012

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

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.

Page 21: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 21/49

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 <= limit); 

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

}

sum = 210

Page 22: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 22/49

Page 23: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 23/49

For example, the following for statement loops five times and each time prints the value of i. Note that the variable i is no t visible any

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

Page 24: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 24/49

 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

Page 25: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 25/49

 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

4. 6. 7. Declare multiple variables in for loop

 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

Page 26: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 26/49

 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

Page 27: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 27/49

 

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.141592653589793radius = 1.2area = 4.523893421169302radius = 1.4area = 6.157521601035994radius = 1.5999999999999999area = 8.04247719318987radius = 1.7999999999999998area = 10.178760197630927radius = 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 12! is 2

3! is 64! is 245! is 1206! is 7207! is 50408! is 403209! is 36288010! is 362880011! is 3991680012! is 47900160013! is 622702080014! is 87178291200

Page 28: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 28/49

15! is 130767436800016! is 2092278988800017! is 35568742809600018! is 640237370572800019! is 12164510040883200020! is 2432902008176640000

4. 6. 13. Java's 'labeled for' loop

 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 = 0continue inneri = 1continue inneri = 2continuei = 3breaki = 4continue inneri = 5continue inneri = 6

Page 29: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 29/49

Page 30: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 30/49

 

4. 7. For Each Loop4. 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(); }

}

Page 31: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 31/49

1 2 3 4 5 6 7 8 9 101 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 springThe season is now summerThe season is now fallThe 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 Collection

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);

}}

Page 32: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 32/49

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: 1Value is: 2Value is: 3Value is: 4Value is: 5Value is: 6Value is: 7Value is: 8Value is: 9Value is: 10Summation: 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); } 

} }

aeiou

Page 33: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 33/49

 

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); 

} }

Value is: 1Value is: 2Value is: 3Value is: 4Value is: 5Value is: 2Value is: 4Value is: 6Value is: 8Value is: 10

Value is: 3Value is: 6Value is: 9Value is: 12Value is: 15Summation: 90

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  

Page 34: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 34/49

  } } System.out.println("Summation of first 5 elements: " + sum); 

} }

Value is: 1Value is: 2Value is: 3

Value is: 4Value is: 5Summation of first 5 elements: 15

Page 35: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 35/49

 

4. 8. Break Statement4. 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 Statement 

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

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

0123

Page 36: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 36/49

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; } 

} } 

}

235711

13171923293137414347535961

Page 37: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 37/49

67717379838997101103107

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

1.  The break statement can be followed by a label.

2.  The presence of a label will transfer control to the start of the code identified by the label.

3.  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;}

Page 38: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 38/49

  }}

}

235711

13171923293137

Page 39: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 39/49

 

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 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); 

Page 40: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 40/49

}

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 12! is 23! is 64! is 245! is 1206! is 720

7! is 50408! is 403209! is 36288010! is 362880012! is 47900160014! is 127894528016! is 200418918418! is -89843302420! 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++) {

Page 41: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 41/49

  if (i % j == 0) {continue OuterLoop;

}}System.out.println(i);

}}

}

2357111317192329313741

4347

Page 42: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 42/49

 

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); 

Page 43: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 43/49

  } 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()); 

} } 

Page 44: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 44/49

 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 

Page 45: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 45/49

  } } 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); } 

} }

Page 46: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 46/49

 

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"); 

Page 47: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 47/49

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(); } 

}

Page 48: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 48/49

 

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) { System.out.println("Exception caught"); 

}  procB();  procC(); } 

}

Page 49: Computer Science Reference Java Statements

8/9/2019 Computer Science Reference Java Statements

http://slidepdf.com/reader/full/computer-science-reference-java-statements 49/49

 

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); } 

} }