Java Note - Controlling Execution

来源:互联网 发布:国产浏览器知乎 编辑:程序博客网 时间:2024/06/07 22:27

Most procedural programming languages have some kind of control statement, and there is often overlap among languages.

True or False

All conditional statements use the truth or falsehood of a conditional expression to determine the execution path.

Java does not allow you to use a number as a boolean.

Selection

The basic way to control program flow is selection

// select an execute path according to boolean expressionif (boolean-exp)    statementelse    statement// select from among pieces of code based on the value of an expressionswitch (exp)case (val_1) :     statement_1; break;case (val_2) :    statement_2; break;default    statment_default; break;

Iteration

Looping is controlled by while, do-while and for, which are sometimes classified as iteration statements.

A statement repeats until the controlling boolean-expression evaluates to false.

// the most common loop syntaxwhile (boolean-exp)    statement// at least execute oncedo    statementwhile (boolean-exp)// be used for countingfor (initialization; boolean-exp; step)    statement// Foreach syntaxfor (type t : iterable-object)    statement

Several keywords represent unconditional branching, which simply means that the branch happens without any test.

return - cause the current method to exit and specify what value the method returnbreak - quit the loop without executing the rest of the statementscontinue - stop the execution of the current iteration and begin the next iteration(label:) - the only place a lable is useful in java is right before an iteration statement

The comma operator

The comma operator has only one use in Java: in the control expression of a for loop

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

for (int i=0, j=0; i < 10; i++, j=i*2)    statement
0 0