Control Flow

Back Up Next

 

Control Flow

Java's control flow constructs are the same as those in C++, minus goto (which is reserved but unused)
Statements and Blocks
Expression statements - assignment, pre/post-fix ++/--, method call, object creation. Ends with ;
Declaration statements - declare variables and optionally initialize its value - can appear ANYWHERE inside a block.
Blocks - group multiple statements into "one" logical statement (a compound statement)
Conditional
if (boolean-expression)
	statement1
else
	statement2
Switch
switch (value-expression) {
	case static-value1:
		statement1
	case static-value2:
		statement2
	...
	default:
		statement
}
fall-throughs and break;
caveat - value-expressions and static-values can't be float/double (imprecise number).
Also, case values must not change (literals or static variables)
While
while (boolean-expression)	//executes 0 or more times
	statement

do
	statement
while (boolean-expression)	//executes 1 or more times
For
for (initial-expression; boolean-expression; incremental-expression)
	statement

unwraps to:

{
	initial-expression;
	while (boolean-expression) {
		statement
		incremental-expression;
	}
}
Labels, Break, and Continue
label-name:
	statement
break [label-name];	//psuedo "goto"
continue;		//skips remainder of loop and eval
Return
if method has no return value, use
return;
if method has a return type,
return value;

where value has type to be returned