Google News
logo
Java - For
Loop control statements:
Loop: A loop is defined as a block of statements which are repeatedly executed for certain number of times.
In other words it iterates a code or group of code many times.

Why use loops: Suppose you want to execute some code/s 10 times. You can perform it by writing that code/s only one time and repeat the execution 10 times using loop. For example: Suppose that you have to print table of 2 then you need to write 10 lines of code, by using loop statements you can do it by 2 or 3 lines of code only.

1. for Loop:

The for loop works well where the number of iterations of the loop is known before the loop is entered. The head of the loop consists of three parts separated by semicolons (;).
a. The first part is the one which runs before the loop is entered. This is usually called the initialization” of the loop variable. This executes only once.
b. The second part is a test. The test condition is a relational expression that determines the number of iterations desired or it determines when to exit from the loop.
a. For loop continues to execute as long as conditional test is satisfied.
b. When the condition becomes false the control of the program exits from the body of for loop and executes next statements after the body of the loop.
c. The third part is a statement to be run every time the loop body is completed. This is usually an increment or decrement of the loop counter.
d. This decides how to make changes in the loop.
Java Images
for program:
class Test 
{ 
public static void main(String[] args) 
{ 
for (int i=0;i<10;i++) 
{ 
System.out.println("hi"); 
} 
} 
}
Output :
output:hi,,hi,,hi,,hi,,hi,,hi,,hi,,hi,,hi,,hi
for without -initialization
class Test 
{ 
public static void main(String[] args) 
{ 
int i=0; 
for (;i<10;i++) 
{ 
System.out.println("freetmielearn"); 
} 
}
}
Output :
10 time's freetmielearn
instead of initialization possible to take System.out.pritnln
class Test 
{ 
public static void main(String[] args) 
{ 
int i=0; 
for (System.out.println("hi");i<10;i++) 
{ 
System.out.println("freetmielearn"); 
} 
}
}
Output :
hi,10times freetmielearn
java infinite loop.
class Test 
{ 
public static void main(String[] args) 
{ 
for (int i=0;;i++) 
{ 
System.out.println("hi"); 
} 
} 
} 
Ex 2:- 
class Test 
{ 
public static void main(String[] args) 
{ 
for (int i=0;true;i++) 
{ 
System.out.println("hi"); 
} 
} 
}
Output :
infinite loop