영어로 읽는 코딩

25_[자바] 콤마 연산자

The comma operator

Earlier in this chapter I stated that the comma operator (not the comma separator, which is used to separate definitions and method arguments) has only one use in Java: in the control expression of a for loop. In both the initialization and step portions of the control expression, you can have a number of statements separated by commas, and those statements will be evaluated sequentially.

Using the comma operator, you can define multiple variables within a for statement, but they must be of the same type:

//: control/CommaOperator.java
public class CommaOperator {
    public static void main(String[] args) {
		for(int i = 1, j = i + 10; i < 5; i++, j = i * 2) {
			System.out.println("i = " + i + " j = " + j);
			}
	}
} /* Output:
i = 1 j = 11
i = 2 j = 4
96 Thinking in Java Bruce Eckel
i = 3 j = 6
i = 4 j = 8
*///:~

The int definition in the for statement covers both i and j. The initialization portion can have any number of definitions of one type. The ability to define variables in a control expression is limited to the for loop. You cannot use this approach with any of the other selection or iteration statements.

You can see that in both the initialization and step portions, the statements are evaluated in sequential order.

 

[Thinking in Java 97]

댓글

댓글 본문
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기