Programming:Java control

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Back to main page

These Java statements allow one to cause code to be executed repeatedly or under certain conditions.

[edit] Loops

while loops cause code to be executed repeatedly as long as a given condition is true.

while (Boolean expression) {
    statement(s)
}

do-while statements cause code to be executed at least once, but are executed again repeatedly if the given condition is true.

do {
    statement(s)
} while (Boolean expression);

for loops allow you to repeat statements a specified number of times. A variable is first initialized, then the statements are repeated until the termination condition is false, with the incrementing expression being performed on the variable for each repeat.

for (initialisation ; termination condition ; incrementing expr) {
    statement(s)
}


[edit] Conditional statements

if statements cause statements to be executed only if a certain condition is true. An optional else block may be added after the if statement. Code within this block is executed when the condition described in the if statement is false.

if (Boolean expression) {
    statement(s)
}


if (Boolean expression) {
    statement(s)
} else {
    statement(s)
}

With else if blocks arbitrarily complex if-then-constructions may be built.

if (Boolean expression) {
    statement(s)
} else if (Boolean expression) {
    statement(s)
} else if (Boolean expression) {
    statement(s)
} else {
    statement(s)
}

switch-case statements jump to a certain part of the code if the constant integer in it's case label matches the given integer expression, or to the default label if none of the case labels match.

switch (integer expression) {
    case constant integer expr:
         statement(s)
         break;
    ...
    default:
         statement(s)
         break;
}
Personal tools
Create a book
  • Add wiki page
  • Collections help