Question

I have come across a somewhat annoying problem during a project. I created this sample class to describe the issue which I am having.

public class Test {
    public static void Testing(){
        for (int i = 0; i >= 5; i++) {
            System.out.println(i);
        }
        System.out.println("hello world."); 
    }

    public static void main(String[] args) {
        Testing();
    }
}

My issue is that the only output from this program is simply "hello world."

Could anyone explain the reason why my println statement inside the for loop is being completely ignored? I have searched on Google but it is hard to describe in a search.

Thanks a lot!

Was it helpful?

Solution

The for loop should be

for (int i = 0; i <= 5; i++)

OTHER TIPS

Hai Buddy. the problem is logical.look at the for loop closely for (int i = 0; i >= 5; i++)

The for loop should be

for (int i = 0; i <= 5; i++)

I think the problem is that you loop never executes since your condition is that I is at least 5, but you start it at zero. Try changing it to be less than or equal to five and see if that fixes it.

change the for loop

for(int i = 0; i <= 5; i++)

read again:

for (int i = 0; i >= 5; i++)

i defaults to zero, and the for iterates while i is more or equal to 5.

Because your condition (i >= 5) never is true, since you set i to 0. The condition should be i <= 5.

 for (int i = 0; i <= 5; i++) //You have put > sign it should be < sign
    {
        System.out.println(i);
    }

The reason is that your for loop is never executed. On first step i = 0 i>=5 = false so the body of the for is never executed

When main method invoke you method it first initialize the value of i with 0 then its go for the condition i>=5, Which looks like 0 >= 5 which always be 'false'.So you inner print statement never be execute.

The for loop never execute because the at the beginning i is checked to see if it equal or greater than 5 (which it is not, i=0)

 for (int i = 0; i >= 5; i++)

then the loop terminates and the next statement is executed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top