Java loops and conditional statements

Java loops and conditional statements

Java if and if-else conditional statement.

An if statement tells the program that it must carry out a specific piece of code if a condition test evaluates to true.

If an else statement is present another section of code will bee executes if the condition test evaluates to false.

Java if and if-else syntax:

...
if ( condition ) // The condition is a boolean expression
statement; // Executes if condition is true// No enclosing block is required when only one statement
[ else {
statement; // Executes if condition is false
statement; // Enclosing block is necessary when more than one statement
}
]
...

You can download this example here(needed tools can be found in the right menu on this page).

Java for loop.

A for loop is divided into three parts, an initialization part, a conditional part and an increment part

You should sett all initial values in the initialization part of the loop.

A true from the condition part will execute subsequent statements bounded by {} brackets. A false from the condition part will end the loop.

For each loop the increment part will be executed.

Java for loop syntax:

...
for ( initialization; condition; incrementor )
statement;
// Initialization are limited to the scope of the for statement// The condition is a boolean expression (if true the body is executed)// Following each execution of the body, the incrementor expressions are evaluated.
...

Java enhanced for loop.

The enhanced for loop can be used to loop over arrays
of any type as well as any kind of
Java object that implements the java.lang.Iterable interface.

Coding example:

...
for ( varDeclaration : iterable )
statement;
// Iterating over a series of values in an array// or other type of collection
...
int [] arrayOfInts = new int [] { 1, 2, 3, 4 };
for( int i : arrayOfInts )
System.out.println( i );
// In this example the enhanced for loop will // print all the values in array, arrayOfInts.
...

Java switch statements.

The switch statement can have a number of possible execution paths.

A switch works with the byte, char, short, and int primitive data types.

It works with enum type (java.lang.Enum).

It also works with java.lang.String class and a few special classes that wrap certain primitive types:
java.lang.Character, java.lang.Byte,
java.lang.Short, and java.lang.Integer.

Must use break to terminate each branch.

Each case will be tested and if none results in a true
condition an optional default path with statements will be executed.