Java - Decision Control and looping statement - For Tutorial
For loop
The Java for loop is used When you exactly know how many times the loop should be executed.
For example- Suppose you want to execute “hello” three-time
public class forloop
{
public static void main(String[] args)
{
for (int i = 0; i < 3; i++)
{//Starting from i=0,0<3 true,then i=1,1<3 true, then i=2,2<3
System.out.println("Hello");
}
}
}
Program explanation-
It Checks for a condition if it is true or not.
My value is set to 0, 0 is less than 3, hence it will print 1st Hello.
I value get incremented by 1,making it i=0+1=1
I=1 is less than 3, true, hence it will print 2nd Hello.
I value get incremented again by 1, making it i=1+1=2
I=2 is less than 3, true, hence it will print 3rd Hello.
I value get incremented again by 1, making it i=2+1=3
I=3 is not less than 3, false, hence the loop will stop.
For-each Loop
This loop will not check the condition, it will print each statement in the array.
public class ForEachLoop
{
public static void main(String[] args)
{
int[] value = {1,2,3,4};
for (int i : value)
{
System.out.println(i);
}
}
}