Java Basic tutorial part Three.

Java FOR LOOP.

The for loop is an entry-controlled loop that allows a user to execute a block of a statement with a fixed number of times. This is the easiest to understand Java loops.

There are three types of for loops in Java.

for(initialization; condition ; increment/decrement)
{
   statement(s);
}

First step: In for loop, initialization part of the loop.

Second step: Condition part of the loop when condition is true the loop body is executing, and condition get false the loop does not execute.

Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that update.

Fourth step: After third step, condition will re executing.

 nt i=1 is initialization expression
i>1 is condition (Boolean expression)
i– Decrement operation.

Infinity for loop.

This is an infinite loop as the condition would never return false This Boolean expression: i>1, it would never return false in this infinity for loop.

Enhanced For loop.

Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand.

This will change depending on the data type of array

Find the sum of natural numbers using for loop.
public class MyfirstApplication {

    public static void main(String[] args) {

       int num = 10, count, total = 0;

       for(count = 1; count <= num; count++){
           total = total + count;
       }

       System.out.println("Sum of first 10 natural numbers is: "+total);
    }
}

When for loop is used.

If the number of iterations is fixed, it is recommended to use for loop.

Java for-each Loop.

Used to define array or collection in program.

It is easier to use than simple for loop.

It works on the basis of elements and not the index
for(data_type variable : array_name){    
//code to be executed    
}    
Java Labeled For Loop.

We can have a name of each Java for loop. To do so, we use label before the for loop.

labelname:    
for(initialization; condition; increment/decrement){    
//code to be executed    
}    
Java Basic tutorial part Three

Java Part one.

One thought on “Java Basic tutorial part Three.”

Leave a Reply

Your email address will not be published. Required fields are marked *