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
    }
    ]
...
Code example:
public class IfelseExample {

  public static void main(String[] args) {
    int[] numbers = {10, 72, 300};
    for (int num : numbers) {
      if (num > 100) {
        System.out.println(num+ " is grater than 100");
      } else if (num > 50) {
        System.out.println(num+ " is grater than 50");
      } else {
        System.out.println(num+ " is less than 50");
      }
    }
  }
}
The result of this is:
10 is less than 50
72 is grater than 50
300 is grater than 100
You can download this example here (needed tools can be found in the right menu on this page).

The conditional (ternary) operator

This operator is frequently used as a shortcut for the if-else statement.
Code example:
// First the syntax
// (expression1) ? (expression2) : (expression3)
...
int z =  (x < y) ? x : y;
// When x > y  then z=x else z=y
...

Java while and do-while loop.

  • while will perform a logical test, and if this results in a true condition execute subsequent statements bounded by {} brackets.
  • do while will first execute statements bounded by {} brackets and than perform a logical test. If the logical test results in a true condition execute the statements bounded by {} brackets again.
Java while and do-while loop syntax::
// The while syntax
while ( condition ){
        statement;  // Statements executes as long as condition is true
        statement;   
}
// This is the do-while syntax
do  {
   statement;       // do-while loop always executes 
   statement;       // its statement body at least once.
   statement;       // Statements executes as long as condition is true
 }
 while ( condition );
Java while example:
public class Whiledemo {
    public static void main(String[] args) {
    int[] numbers = {10, 72, 300};
    int num=0;
    while(num<numbers.length) {
      if (numbers[num] > 100) {
        System.out.println(numbers[num]+ " is grater than 100");
      } else if (num > 50) {
        System.out.println(numbers[num]+ " is grater than 50");
      } else {
        System.out.println(numbers[num]+ " is less than 50");
      }
      num++;
    }
  }
}
The result of this is:
10 is less than 50
72 is less than 50
300 is grater than 100
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.  
...
Coding example:
// Use of  multiple comma-separated
// expressions in the initialization
// and in the incrementation sections.
for (int i = 0, j = 100; i < 100; i++, j-- ) {
  System.out.println( i  );      
  System.out.println( j  );     
}                               
...
int x; // Initialize existing variables from outside the scope of the for loop 
for( x = 0; hasMoreValue(  ); x++ ) // In this case a method 
   getNextValue(  );                // is returning the condition
System.out.println( x );
...

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.
Switch syntax:
...
for ( initialization; condition; incrementor )
    statement;
switch ( int expression )
 {
     case int constantExpression :
         statement; break;
     [ case int constantExpression
         statement; break; ]
     ...
     [ default :
         statement;  ]
 }
...
Switch example:
public class SwitchDemo {

  public static void main(String[] args) {
    for (int mnd = 1; mnd <= 6; mnd++) {
      int days = 31;
      switch (mnd) {
        case 2:
          days = 29;
          break;
        case 4:
        case 6:
          days = 30;
          break;
      }
      for (int day = 1; day <= days; day++) {
        String  pre="";
        if (day<10) {
          pre="0";
        }
        System.out.print(pre+day + "." + mnd + "." + "2008 ");
        if (day % 10 == 0){
          System.out.println();
        }
      }
      System.out.println();
    }
  }
The result of this is:
01.1.2008 02.1.2008 03.1.2008 04.1.2008 05.1.2008 06.1.2008 07.1.2008 08.1.2008 09.1.2008 10.1.2008 
11.1.2008 12.1.2008 13.1.2008 14.1.2008 15.1.2008 16.1.2008 17.1.2008 18.1.2008 19.1.2008 20.1.2008 
21.1.2008 22.1.2008 23.1.2008 24.1.2008 25.1.2008 26.1.2008 27.1.2008 28.1.2008 29.1.2008 30.1.2008 
31.1.2008 
01.2.2008 02.2.2008 03.2.2008 04.2.2008 05.2.2008 06.2.2008 07.2.2008 08.2.2008 09.2.2008 10.2.2008 
11.2.2008 12.2.2008 13.2.2008 14.2.2008 15.2.2008 16.2.2008 17.2.2008 18.2.2008 19.2.2008 20.2.2008 
21.2.2008 22.2.2008 23.2.2008 24.2.2008 25.2.2008 26.2.2008 27.2.2008 28.2.2008 29.2.2008 
01.3.2008 02.3.2008 03.3.2008 04.3.2008 05.3.2008 06.3.2008 07.3.2008 08.3.2008 09.3.2008 10.3.2008 
11.3.2008 12.3.2008 13.3.2008 14.3.2008 15.3.2008 16.3.2008 17.3.2008 18.3.2008 19.3.2008 20.3.2008 
21.3.2008 22.3.2008 23.3.2008 24.3.2008 25.3.2008 26.3.2008 27.3.2008 28.3.2008 29.3.2008 30.3.2008 
31.3.2008 
01.4.2008 02.4.2008 03.4.2008 04.4.2008 05.4.2008 06.4.2008 07.4.2008 08.4.2008 09.4.2008 10.4.2008 
11.4.2008 12.4.2008 13.4.2008 14.4.2008 15.4.2008 16.4.2008 17.4.2008 18.4.2008 19.4.2008 20.4.2008 
21.4.2008 22.4.2008 23.4.2008 24.4.2008 25.4.2008 26.4.2008 27.4.2008 28.4.2008 29.4.2008 30.4.2008 

01.5.2008 02.5.2008 03.5.2008 04.5.2008 05.5.2008 06.5.2008 07.5.2008 08.5.2008 09.5.2008 10.5.2008 
11.5.2008 12.5.2008 13.5.2008 14.5.2008 15.5.2008 16.5.2008 17.5.2008 18.5.2008 19.5.2008 20.5.2008 
21.5.2008 22.5.2008 23.5.2008 24.5.2008 25.5.2008 26.5.2008 27.5.2008 28.5.2008 29.5.2008 30.5.2008 
31.5.2008 
01.6.2008 02.6.2008 03.6.2008 04.6.2008 05.6.2008 06.6.2008 07.6.2008 08.6.2008 09.6.2008 10.6.2008 
11.6.2008 12.6.2008 13.6.2008 14.6.2008 15.6.2008 16.6.2008 17.6.2008 18.6.2008 19.6.2008 20.6.2008 
21.6.2008 22.6.2008 23.6.2008 24.6.2008 25.6.2008 26.6.2008 27.6.2008 28.6.2008 29.6.2008 30.6.2008 
You can download this example here (needed tools can be found in the right menu on this page).

Java break/continue statements.

A break causes Java to stop the current block statement and resume execution after it:
...
while( true ) {
        if ( condition(  ) )
             break;
    }
    // after while
...
A continue statement causes loops to move on to their next iteration by returning to the point where they check their condition:
...
for( int i=0; i < 100; i++ ) {
        if ( i == 33 )
            continue;
        System.out.println( i );
    }

...
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.