Chapter 10 Control Flow

1) A switch statement allows you to transfer control to a labeled entry point in a block of statements, based on the value of an expression. The general form of a switch statement is:

switch (expression) {
    case n: statements
    case m: statements
    . . .
    default: statements
}

The expression must either be of an integer type (char, byte, short, or int, or a corresponding wrapper class) or an enum type.

 

2) Enhanced for(for-each loop):

for (Type loop-variable : set-expression)
     statement

  The set-expression must evaluate to an object that defines the set of values that you want to iterate through, and the loop-variable is a local variable of a suitable type for the set's contents. Each time through the loop, loop-variable takes on the next value from the set, and statement is executed (presumably using the loop-variable for something). This continues until no more values remain in the set.

Example:

public class EnhancedFor {
	static int sum(int []a) {
		int sum = 0;
		for(int val : a) sum += val;
		return sum;
	}

	public static void main(String[] args) {
		int[] a = {1,2,3,4,5};
		System.out.println(sum(a));
	}
}

Output:

15

 

The set-expression must either evaluate to an array instance, or an object that implements the interface java.lang.Iterable which is the case for all of the collection classes. The main motivation behind the enhanced for statement is to make it more convenient to iterate through collection classes, or more generally anything that implements the Iterable interface.

 

3) You can label statements to give them a name by which they can be refered by break or continue;

label : statement

There are two forms of break statement, the unlabeled break:

break

and the labeled break;

break label;

  The labeled one is especially useful in the multi-loop circumstance.

Example:

public static void main(String[] args) {
		int i = 0, j = 0;
		
		loop : 
		for(i = 0; i < 5; ++i){
			for(j = 0; j < 5; ++j) {
				if(i == 3 && j == 4) break loop;
			}
		}

		System.out.println("i: " + i + ", j: " + j);
	}

Output:

i: 3, j: 4

 

  Like the break statement, the continue statement has an unlabeled form:

continue;

and a labeled form:

continue label;

In the unlabeled form, continue transfers control to the end of the innermost loop’s body. The labeled form transfers control to the end of the loop with that label. The label must belong to a loop statement.

Example:

public static void main(String[] args) {
		int i = 0, j = 0;
		
		loop:
			for(i = 0; i < 3; ++i ) {
				for(j = 0; j < 3; ++j) {
					if(j > i) continue loop;
					else System.out.println(i + ", " + j);
				}
			}
	}

Output:

0, 0
1, 0
1, 1
2, 0
2, 1
2, 2

 

4) Although goto is a reserved keyword in Java, the Java programming language has no goto construct that transfers control to an arbitrary statement like in C or C++.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章