In this post we can see how to implement in Java, the basic flow control structures / statements:
-
decision-making structures: if – then, if – then – else, switch;
-
structures for loop blocks: do-while, while – do, enhanced – for;
-
loop control instructions: break, continue;
Using control structures we can write programs for which the execution is not just a linear sequence of instructions.
Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial – Contents.
How to use in Java if – then control statement
The conditional flow control structure, if – then, has these forms:
1: if (condition)
2: < statement 1 >
or
1: if (condition) {
2: < statement 1 >
3: < statement 2 >
4: }
in which (WARNING !) condition is a boolean expression or variable that has the value true or false .For example 30> 10 or 10 == 30.
In Java are not accepted conditions based on expressions or variables that have numeric values. For example, the following expression is valid in C / C + + but not in Java:
int valoare = 10;
if(valoare)
System.out.println("Other than 0 value !");
generates a compilation error: incompatible types.
To illustrate the if-then clause, we determine whether a number is negative, and if it is then change its sign:
int negativeNumber = -22;
boolean isNumber = true;
if(isNumber)
System.out.println("It's a number";);
if(negativeNumber < 0)
{
System.out.println("It's a negative one! Change it.");
negativeNumber = (-1) *negativeNumber;
System.out.println(negativeNumber);
}
How to use in Java if – then – else control statement
The if – then – else control clause has this form:
1: if (condition){
2: < statement 1 >
3: < statement 2 >
4: }
5: else{
6: < statement 3 >
7: < statement 4 >
8: }
If we want to determine the minimum of two numbers:
int vb1 = 10;
int vb2 = 20;
int min;
if(vb1 < vb2)
min = vb1;
else
min = vb2;
The same solution can be implemented through the conditional operator?::
condition ? then_statement : else_statement
And the previous example becomes:
min = vb1 < vb2 ? vb1 : vb2;
How to use in Java do – while loops
The repetitive structures do - while implements a post-conditioning loop, as the condition for exiting/staying in the loop is checked at the end of the loop block. The structure will run at least once the iteration statements from the loop block:
1: do
2: {
3: < statement 1 >
4: < statement 2 >
5: } while (conditie);
For example, if we want to compute N! (Provided that N> 1) in a do - while:
//n factorial using do - while with this condition n > 0
int nFactorial = 1;
int i = 0;
int n = 5;
do
{
i++;
nFactorial = nFactorial *i;
}while(i < n);
//print the value
System.out.println(n+"! = "+nFactorial);
How to use in Java while – do loop
The repetitive structure while - do implements a pre-conditioning cycle, as the condition for exiting from/staying in the loop is checked before the first statement in the loop block is executed:
1: while (condition)
2: {
3: < statement 1 >
4: < statement 2 >
5: }
Acelasi exemplu, N!, dar prin while – do:
//n factorial with while - do
int nFactorial = 1;
int i = 0;
int n = 5;
while (i < 5)
{
i++;
nFactorial = nFactorial *i;
}
//afisam valoarea
System.out.println(n+"! = "+nFactorial);
How to use in Java the for loop
The for repetitive structure implements a pre-conditioned loop structure, like do-while . The for structure is more efficient, simply because the iteration and the initialization statements are included in the structure and not in the block:
1: for(initialization; condition; iteration)
2: {
3: < statement 1 >
4: < statement 2 >
5: }
For example, to determine the sum of an array elements:
int[] vector = {1,2,3,4,5};
int sum = 0;
for(int j = 0; j < vector.length; j++)
sum += vector[j];
System.out.println("The sum is "+sum);
Inside the for control structure can be written multiple iteration and initialization statements separated by , (comma):
1: for(initialization1, initialization2; condition; iteration1, iteration2)
2: {
3: < statement 1 >
4: < statement 2 >
5: }
The for statement elements: initialization, iteration and condition, are optional. The next examples are legal, but in some you must decide when the for loop will end using break.
for( intialization; ; )
for( ; condition; iteration )
for( ; ; iteration)
for( ; ; ) // endless loop
For the SCJP exam, keep in mind that variables declared in the initialization area, are local variables for the for block and are not visible outside:
for ( int i=0; i<10 ; i++ ) {
// do something
}
// compile-error, cannot resolve symbol: i
System.out.println("value of i: " + i );
How to use in Java the enhanced - for loop
The repetitive enhanced - for structure implements a pre-conditioned loop. This structure was introduced in Java 5.0 to allow an easier syntax and a faster implementation (like foreach from. NET). This structure can only be used to iterate through a collection that implements the java.lang.Iterable interface.
1: for ( variable: iterable_collection )
2: {
3: < statement 1 >
4: < statement 2 >
5: }
6:
Rewriting the previous example with an enhanced – for:
sum = 0;
for(int value: vector)
{
suma += value;
}
System.out.println("The sum is "+sum);
How to use in Java the switch statement
The switch conditional structure implements a conditional structure with multiple branches. It replacea a more efficient structure than multiple if-then-else clauses.
1: switch (variable) {
2: case constant_value1:
3: < statement 1 >
4: break;
5: case constant_value2:
6: < statement 2 >
7: break;
8: …
9: default:
10: < statement >
11: }
It is important that each case clause is closed with the break instruction because it provides the exit from the switch structure.
For example testing a variable value can be made more easier through a switch statement than through multiple if statements.
int testValue = 2;
switch(testValue)
{
case 1:
System.out.println("The value is 1");
break;
case 2:
System.out.println("The value is 2");
break;
case 3:
System.out.println("The value is 3");
break;
case 4:
System.out.println("The value is 4");
break;
default:
System.out.println("The value is outside the limits");
}
By running the above example we obtain this message: Value is equal to 2.
If we don’t use break instructions then the previous example is going to display:
The value is 2
The value is 3
The value is 4
The value is outside the limits
How to use in Java break and continue statements
The break statement stops the current loop block implemented by for, do-while, while-do. Also, if it is used in a switch structure, it will close the last case clause.
The continue instruction will suspend the current iteration of a loop block, for, do-while, while-do and will execute the next iteration.
For example, let’s determine the sum of all positive elements of a given array:
int[] intValues = {10,12,5,-4,3,-1,23};
int positiveSum = 0;
for(int j = 0; j < intValues.length; j++)
{
if(intValues[j] < 0) //if it is a negative value
continue; //go to the next iteration
//for any other values we do the sum
positiveSum+=valoriInt[j];
}
System.out.println("The sum of positive elements is "+positiveSum);
or, let’s determine the first occurrence of a negative value:
int[] intValues = {10,12,5,-4,3,-1,23};
int negativeValue = 0;
for(int j = 0; j < intValues.length; j++)
{
if(intValues[j] < 0)
{
//if it is a negative value
//save the value
negativeValue = intValues[j];
//stop the loop
break;
}
}
System.out.println("The first negative value is "+negativeValue);
Other topics that are part of this Java tutorial are accessible through Java 6 Tutorial - Contents.