Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are asking if infinite loops can be useful, the answer is yes. There are plenty of situations where you want something running forever, though the loop will usually be terminated at some point. </p> <p>As to your question: "Can java recognized when a loop will be infinite?" The answer is that it is impossible for a computer to have an algorithm to determine if a program will run forever or not. Read about: <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="nofollow noreferrer">Halting Problem</a> </p> <p>Reading a bit more, your question is also asking why the doSomething() function does not complain that it is not returning an int.</p> <p>Interestingly the following source does NOT compile.</p> <pre><code>public class test { public static int doSomething() { //while(true); boolean test=true; while(test){ } } public static void main(String[] args) { doSomething(); } } </code></pre> <p>This indicates to me that, as the wiki page on the halting problem suggests, it is impossible for there to be an algorithm to determine if every problem will terminate, but this does not mean someone hasn't added the simple case:</p> <pre><code>while(true); </code></pre> <p>to the java spec. My example above is a little more complicated, so Java can't have it remembered as an infinite loop. Truely, this is a weird edge case, but it's there just to make things compile. Maybe someone will try other combinations. </p> <p>EDIT: not an issue with unreachable code.</p> <pre><code>import java.util.*; public class test { public static int doSomething() { //while(true); while(true){ System.out.println("Hello"); } } public static void main(String[] args) { doSomething(); } } </code></pre> <p>The above works, so the while(true); isn't being ignored by the compiler as unreachable, otherwise it would throw a compile time error!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload