1

Hello World, am kinda new To java and oop and I would like to ask if an infinite loop needs an increment for example

     for(int i = 0;i < 4;i++) {
       System.out.print("Hello World");
     }

so in this loop, there is an increment, so do all types of loop need increment

1
  • 1
    No; the increment and test are both optional. Although the idiomatic way to write an infinite loop is just while (true). Apr 12, 2014 at 13:55

4 Answers 4

6

This loop:

for(int i = 0;i < 4;i++) {
   System.out.print("Hello World");
 }

is not infinite. It will iterate 4 times, then end. If you wanted an infinite loop, then you could do this:

for(;;) {
   System.out.print("Hello World");
 }

or:

while(true)
{
   System.out.print("Hello World");
}

So no, only the separating semi-colons in a for loop are required.

4

No, if you want to run an infinite loop you could use while(true)

while (true) {
  System.out.print("Hello World");
}

With your for you are just doing an useless thing (increment i every time).

If you need to keep a "number of times"

int x = 0;
while (true) {
  System.out.print("Hello World");
  ++x;
}

Or, a for without condition (for(;;) is legal!) with

for (int x = 0; ; ++x)
{
  System.out.print("Hello World");
}
6
  • will it crash the program and my pc if the increments is not declared
    – Favor
    Apr 12, 2014 at 13:56
  • Yes, you cannot let run something forever (in this way). You need to stop it or your application will be killed as "Not responsive" Apr 12, 2014 at 13:57
  • It won't crash the PC (that's a lot harder these days). Apr 12, 2014 at 13:58
  • is there a way I can do that(stop it )
    – Favor
    Apr 12, 2014 at 13:58
  • 1
    @user3526881: "is there a way I can do that(stop it )" The best way is to have a reasonable condition in the while (or for) in the first place. Writing an "infinite" loop you break out of is very much a poor second choice. Apr 12, 2014 at 14:00
2

Infinite loop with for :

for(;;) {
   System.out.print("Hello World");
 }

Indeed there are infinite ways to create an infinite loop with either for or while or do..while statements, if only the condition never satisfies.

2

Infinite loop using for()

for(;;) {
    System.out.print("Hello World");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.