Menu
Question Index
...

Compare the following programs ForSample1, ForSample2 and WhileSample

class ForSample1
{
    public static void main(String s[])
    {
        for(int i = 0; i <= 5; i++ )
        {
            System.out.println("i = " + i );
        }
    }
}

class ForSample2
{
    public static void main(String s[])
    {
        int i = 0;
        for( ;i <= 5; )
        {
            System.out.println("i = " + i );
            i++;
        }
    }
}

class WhileSample
{
    public static void main(String s[])
    {
        int i =0;

        while(i <= 5)
        {
            System.out.println("i = " + i );
            i++;
        }
    }
}


Output of all the three programs is same.
Output of ForSample1 and ForSample2 is same, but they are different from WhileSample.
Output of ForSample2 and WhileSample is same, but they are different from ForSample1.
ForSample2 does not compile since there is no code before first semicolon and no code after second semicolon.

Doubts

Problems

Topic: for Vs while Loop In Java

Read this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App