Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could this code potentially result in an infinite loop?

Is there any value that could be assigned to the myString variable that would result in an infinite loop in the code below?

while (true) {
    if (myString.indexOf("  ") == -1) {
        break;
    }
    myString = myString.replaceAll("  ", " ");
}
like image 987
user3146723 Avatar asked Dec 30 '13 15:12

user3146723


People also ask

How do you know if its an infinite loop?

In each iteration you calculate a number (the sum of the squares of the digits or the previous number). You can put all those numbers in a Set. If in some iteration you calculate a number that is already in that Set, you know that you are stuck in an infinite loop.

Why is my code in an infinite loop?

Basically, the infinite loop happens when the condition in the while loop always evaluates to true. This can happen when the variables within the loop aren't updated correctly, or aren't updated at all.

What is an infinite loop give an example?

What is an Infinite Loop? An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.

Can you have an infinite for loop?

You can run a for loop infinitely by writing it without any exit condition.


2 Answers

Could this code potentially result in an infinite loop?

No. But if might throw an exception if myString is null.

If the String doesn't contain two spaces, it'll break; after the first iteration. Otherwise, it does contain two spaces, and it replaces it with one space, then, it won't have two spaces again, and it'll break;.

like image 127
Maroun Avatar answered Sep 20 '22 00:09

Maroun


No, it won't - however the loop could be much better structured:

while (myString.indexOf("  ") != -1) {
    myString = myString.replaceAll("  ", " ");
}

Sometimes you need break in a loop, but if you don't need it you should avoid it.

A better solution of course would be to not use a loop at all, remember that replaceAll works from regex:

myString = myString.replaceAll("[ ]+", " ");

For example:

String str = "this is a   test      string with long     white space    chunks";
System.out.println(str.replaceAll("[ ]+", " "));

Try it here: http://www.tryjava8.com/app/snippets/52c19090e4b00bdc99e8a943

like image 31
Tim B Avatar answered Sep 20 '22 00:09

Tim B