0

My question is that if there is a code,

class loop
{
   public static void main()
   {
      for (int i=0; ; i++)
      {
         System.out.println(i)
      }
   }
}

The integer variable i have a max value of 2147483647 (according to google) so will the code run 2147483647 times? If so then it would not be an infinite loop.

Can anyone answer my query?

  • Have you actually tried running the code? That's generally the best way to know the behavior for certain. What I imagine will happen is the integer will overflow (instead of throwing a max-value-reached exception). – h0r53 Jul 23 '21 at 16:24
  • 1
    Have you tried it? Maybe with `byte`? – JonSG Jul 23 '21 at 16:24
  • 1
    I also can't begin to understand why this question, something clearly testable and a duplicate, is upvoted multiple times while there are plenty of good questions with excellent answers that are downvoted. – h0r53 Jul 23 '21 at 16:29
  • 1
    Is something really endless in this cruel world? Your program will stop working. One way or another. But it will stop. Maybe it's because it naturally finishes. Maybe because the JVM has an error, maybe it halts, maybe the VM running it is terminated, maybe it suffers a power issue. Nothing, **nothing** is really endless in this cruel world. It's up to you to try to define how long your program will run. But, my friend, it will stop. Whether you want it or not. – Alberto S. Jul 23 '21 at 16:34
  • 1
    infinite loop that's really infinite: `while (true) { System.out.println("infinite"); }` – Stephen P Jul 23 '21 at 16:42
  • If you really want to see whether this loop is infinite or not, you can change the loop from `for (int i=0; ; i++)` to `for (int i=0; ; i = i + 10000)`. If the loop is finite, then it will stop after a few iterations and if it is infinite, it will not stop at any moment. If you write `for (int i=0; true ; i++)`, then it will obviously be infinite loop. – Utkarsh Sahu Aug 11 '21 at 10:45

2 Answers2

5

Think about what happens when you increment an int already at its max value:

public static void main(String[] args) {
    int x = 2147483647;
    x++;
    System.out.println(x); // -2147483648
}

it won't error, it will just roll over to the negative. So, to answer your question, yes, it will run forever (or until the program is terminated through some external factor)

dave
  • 62,300
  • 5
  • 72
  • 93
0

it will always be an infinite loop because you have no conditions:

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

the value that will shows after 2147483647 will be a negative value.

DEV
  • 1,607
  • 6
  • 19
  • 1
    No conditions doesn't necessarily imply an infinite loop. Within such a loop you could break, call a function, throw an exception, etc. But yes in this case the integer will roll over after reaching its max value. – h0r53 Jul 23 '21 at 16:33
  • yes that's right. i'm meant for this particular loop – DEV Jul 23 '21 at 16:34