DEV Community

velvizhi Muthu
velvizhi Muthu

Posted on

Module 2 : While and For loop syntax

While and for basic:

01.What is While in JAVA?
The while loop in Java is a control flow statement that repeats a block of code as long as a condition is true.

02.How it works:
The condition is checked before each loop.
If the condition is true, the block runs.
After the block finishes, the condition is checked again.
This continues until the condition becomes false.

Important Notes:
If the condition is false at the start, the loop runs 0 times.
If you forget to update the condition (e.g. i++), the loop may become infinite.

03.What is "for" in JAVA?
The for loop in Java is a control structure that allows you to repeat a block of code a specific number of times. It’s commonly used when the number of iterations is known in advance.

04.How it works:
Initialization: runs once at the start (e.g., int i = 0)
Condition: checked before each loop; loop runs while this is true
Update: runs after each loop iteration (e.g., i++)

Example Program:

System.out.println(1);
    System.out.println(1);
    System.out.println(1);
    System.out.println(1);
    System.out.println(1);
Enter fullscreen mode Exit fullscreen mode

    int no = 1;
    while(no <= 5) 
    {
        System.out.println(1); 
        no++; 
    }
Enter fullscreen mode Exit fullscreen mode

    for(int no = 1;no <= 5; no++)
    {
        System.out.println(no); 
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)