Issue
I searched google and stack overflow for this but i didn't get any answer for this question. Here, In this code there is an empty infinite loop and after that it prints "Hello, World". Theoretically, after the infinite loop nothing should be printed after the infinite loop. But when we run the code, it prints "Hello, World". So, Why is the code written after an infinite loop executing?
public class Main{
public static void main(String[] args){
for(int i=0; i>=0; i++){}
System.out.println("Hello, World");
}
}
Thank you.
Solution
This loop is not an infinite loop. It goes until the i reaches Integer.MAX_VALUE. Then i becomes Integer.MIN_VALUE which is a negative value. Run the code below and check the output.
int x = Integer.MAX_VALUE;
x++;
System.out.println(x);
If you want the loop to be infinite use,
for ( ; ; ){
}
Answered By - Roshana Pitigala
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.